Skip to content

Commit

Permalink
Introduce debug memory monitoring
Browse files Browse the repository at this point in the history
that alerts and prints additional debug information in case that Poseidon exceeds 1 GB of memory usage.
  • Loading branch information
mpass99 committed Sep 19, 2023
1 parent c83bdbf commit 4ea328f
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions cmd/poseidon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"net/http"
"os"
"os/signal"
"runtime"
"runtime/debug"
"runtime/pprof"
"strconv"
Expand Down Expand Up @@ -110,6 +111,41 @@ func initProfiling(options config.Profiling) (cancel func()) {
return cancel
}

// watchMemoryAndAlert monitors the memory usage of Poseidon and sends an alert if it exceeds a threshold.
func watchMemoryAndAlert() {
// We assume that Poseidon usually takes about 50-300 MB of memory. Therefore, we specify the threshold of 1 GB.
// Improve: Make this value dynamic or relative.
const threshold = 1 * 1000 * 1000 * 1000
const interval = 5 * time.Second

for {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
log.WithField("heap", stats.HeapAlloc).Trace("Current Memory Usage")

if stats.HeapAlloc >= threshold {
log.WithField("heap", stats.HeapAlloc).Warn("Memory Threshold exceeded")

err := pprof.Lookup("heap").WriteTo(os.Stderr, 1)
if err != nil {
log.WithError(err).Warn("Failed to log the heap profile")
}

Check warning on line 132 in cmd/poseidon/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/poseidon/main.go#L127-L132

Added lines #L127 - L132 were not covered by tests

err = pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
if err != nil {
log.WithError(err).Warn("Failed to log the goroutines")
}

Check warning on line 137 in cmd/poseidon/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/poseidon/main.go#L134-L137

Added lines #L134 - L137 were not covered by tests
}

select {
case <-time.After(interval):
continue
case <-context.Background().Done():
return

Check warning on line 144 in cmd/poseidon/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/poseidon/main.go#L143-L144

Added lines #L143 - L144 were not covered by tests
}
}
}

func runServer(server *http.Server, cancel context.CancelFunc) {
defer cancel()
defer shutdownSentry() // shutdownSentry must be executed in the main goroutine.
Expand Down Expand Up @@ -240,6 +276,7 @@ func main() {
defer cancelInflux()

stopProfiling := initProfiling(config.Config.Profiling)
go watchMemoryAndAlert()

ctx, cancel := context.WithCancel(context.Background())
server := initServer(ctx)
Expand Down

0 comments on commit 4ea328f

Please sign in to comment.