Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

remove old files

p0nycd872056fadc
diff --git a/backend/runner/monitor/monitor.go b/backend/runner/monitor/monitor.go
index de1666880f..269b87abec 100644
--- a/backend/runner/monitor/monitor.go
+++ b/backend/runner/monitor/monitor.go
@@ -11,6 +11,12 @@ import (
"sync"
"time"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
)
@@ -56,42 +62,113 @@ func (r *MemoryMonitor) checkMemory(memoryThreshold uint64) {
if m.Sys >= memoryThreshold {
now := time.Now().UnixMicro()
+
+ // Dump heap profile
heapFileName := filepath.Join(r.profile.DataDir, fmt.Sprintf("memory_dump_%d.prof", now))
slog.Info("memory monitor: memory allocated exceeds memory threshold. will dump pprof memory and goroutine profile", "memoryUsage", m.Sys, "memoryThreshold", memoryThreshold)
slog.Info("memory monitor: dumping pprof memory profile", "fileName", heapFileName)
- fHeap, err := os.Create(heapFileName)
- if err != nil {
- slog.Info("memory monitor: could not create memory profile file", "fileName", heapFileName, log.BBError(err))
+
+ if err := dumpHeapProfile(heapFileName); err != nil {
+ slog.Info("memory monitor: could not dump memory profile", "fileName", heapFileName, log.BBError(err))
// Continue to attempt goroutine dump even if heap dump fails
} else {
- defer fHeap.Close() // Close the file promptly
- // Write the heap profile
- if err := pprof.WriteHeapProfile(fHeap); err != nil {
- slog.Info("memory monitor: could not write memory profile", "fileName", heapFileName, log.BBError(err))
- } else {
- slog.Info("memory monitor: successfully wrote memory profile", "fileName", heapFileName)
+ if err := retainMostRecentFiles(r.profile.DataDir, 5); err != nil {
+ slog.Info("memory monitor: failed to cleanup old dump files after heap dump", log.BBError(err))
}
}
- // It's often useful to also dump goroutine state
+ // Dump goroutine profile
goroutineFileName := filepath.Join(r.profile.DataDir, fmt.Sprintf("goroutine_dump_%d.prof", now))
slog.Info("memory monitor: dumping pprof goroutine profile", "fileName", goroutineFileName)
- fGoroutine, err := os.Create(goroutineFileName)
- if err != nil {
- slog.Info("memory monitor: could not create goroutine profile file", "fileName", goroutineFileName, log.BBError(err))
- return // Return if we cannot create the goroutine file either
+
+ if err := dumpGoroutineProfile(goroutineFileName); err != nil {
+ slog.Info("memory monitor: could not dump goroutine profile", "fileName", goroutineFileName, log.BBError(err))
+ } else {
+ if err := retainMostRecentFiles(r.profile.DataDir, 5); err != nil {
+ slog.Info("memory monitor: failed to cleanup old dump files after goroutine dump", log.BBError(err))
+ }
}
- defer fGoroutine.Close()
+ }
+}
- goroutineProfile := pprof.Lookup("goroutine")
- if goroutineProfile == nil {
- slog.Info("memory monitor: could not look up goroutine profile")
- return
+func retainMostRecentFiles(dir string, retainCount int) error {
+ // Handle memory dumps
+ if err := retainMostRecentFilesByPattern(dir, "memory_dump_*.prof", retainCount); err != nil {
+ return errors.Errorf("failed to retain memory dumps: %v", err)
+ }
+
+ // Handle goroutine dumps
+ if err := retainMostRecentFilesByPattern(dir, "goroutine_dump_*.prof", retainCount); err != nil {
+ return errors.Errorf("failed to retain goroutine dumps: %v", err)
+ }
+
+ return nil
+}
+
+func dumpHeapProfile(fileName string) error {
+ f, err := os.Create(fileName)
+ if err != nil {
+ return errors.Errorf("could not create memory profile file: %v", err)
+ }
+ defer f.Close()
+
+ return pprof.WriteHeapProfile(f)
+}
+
+func dumpGoroutineProfile(fileName string) error {
+ f, err := os.Create(fileName)
+ if err != nil {
+ return errors.Errorf("could not create goroutine profile file: %v", err)
+ }
+ defer f.Close()
+
+ goroutineProfile := pprof.Lookup("goroutine")
+ if goroutineProfile == nil {
+ return errors.New("could not look up goroutine profile")
+ }
+
+ return goroutineProfile.WriteTo(f, 0)
+}
+
+func retainMostRecentFilesByPattern(dir, pattern string, retainCount int) error {
+ matches, err := filepath.Glob(filepath.Join(dir, pattern))
+ if err != nil {
+ return err
+ }
+
+ type fileInfo struct {
+ path string
+ timestamp int64
+ }
+
+ files := make([]fileInfo, 0, len(matches))
+ for _, path := range matches {
+ // Extract timestamp from filename
+ base := filepath.Base(path)
+ // Find the last underscore and extract everything after it until .prof
+ if idx := strings.LastIndex(base, "_"); idx != -1 {
+ timestampStr := strings.TrimSuffix(base[idx+1:], ".prof")
+ timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
+ if err != nil {
+ slog.Info("memory monitor: failed to parse timestamp from filename", "file", base, log.BBError(err))
+ continue
+ }
+ files = append(files, fileInfo{path: path, timestamp: timestamp})
}
- if err := goroutineProfile.WriteTo(fGoroutine, 0); err != nil {
- slog.Info("memory monitor: could not write goroutine profile", "fileName", goroutineFileName, log.BBError(err))
- } else {
- slog.Info("memory monitor: successfully wrote goroutine profile", "fileName", goroutineFileName)
+ }
+
+ // Sort files by timestamp in descending order (most recent first)
+ sort.Slice(files, func(i, j int) bool {
+ return files[i].timestamp > files[j].timestamp
+ })
+
+ // Remove older files beyond retention count
+ for i := retainCount; i < len(files); i++ {
+ slog.Info("memory monitor: removing old dump file", "file", files[i].path)
+ if err := os.Remove(files[i].path); err != nil {
+ slog.Info("memory monitor: failed to remove old dump file", "file", files[i].path, log.BBError(err))
}
}
+
+ return nil
}