diff --git a/cmd/harmony/main.go b/cmd/harmony/main.go index 27731b7d6..3d50b8201 100644 --- a/cmd/harmony/main.go +++ b/cmd/harmony/main.go @@ -122,12 +122,6 @@ var ( "Do not propose view change (testing only)") ) -// Constants for GC. -const ( - // Run garbage collector every 30 minutes. - gcTime = 30 * time.Minute -) - func initSetup() { if *versionFlag { printVersion(os.Args[0]) @@ -199,22 +193,10 @@ func initSetup() { // Set up manual call for garbage collection. if *enableGC { - maybeCallGCPeriodically() + memprofiling.MaybeCallGCPeriodically() } } -// Run GC manually every 30 minutes. This is one of the options to mitigate the OOM issue. -func maybeCallGCPeriodically() { - go func() { - for { - select { - case <-time.After(gcTime): - runtime.GC() - } - } - }() -} - func createGlobalConfig() *nodeconfig.ConfigType { var err error var myShardID uint32 diff --git a/internal/memprofiling/lib.go b/internal/memprofiling/lib.go index 73e913a99..3d15786c0 100644 --- a/internal/memprofiling/lib.go +++ b/internal/memprofiling/lib.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" "reflect" + "runtime" "sync" "time" @@ -18,9 +19,11 @@ const ( MemProfilingPortDiff = 1000 // Constants of for scanning mem size. memSizeScanTime = 30 * time.Second + // Run garbage collector every 30 minutes. + gcTime = 10 * time.Minute ) -// MemProfiling is the struct of MemProfiling. +// MemProfiling is the struct to watch objects for memprofiling. type MemProfiling struct { h *memsizeui.Handler s *http.Server @@ -88,3 +91,32 @@ func (m *MemProfiling) PeriodicallyScanMemSize() { } }() } + +// MaybeCallGCPeriodically runs GC manually every gcTime minutes. This is one of the options to mitigate the OOM issue. +func MaybeCallGCPeriodically() { + go func() { + for { + select { + case <-time.After(gcTime): + PrintMemUsage("mem stats before GC") + runtime.GC() + PrintMemUsage("mem stats after GC") + } + } + }() +} + +// PrintMemUsage prints memory usage. +func PrintMemUsage(msg string) { + var m runtime.MemStats + runtime.ReadMemStats(&m) + utils.GetLogInstance().Info(msg, + "alloc", bToMb(m.Alloc), + "totalalloc", bToMb(m.TotalAlloc), + "sys", bToMb(m.Sys), + "numgc", m.NumGC) +} + +func bToMb(b uint64) uint64 { + return b / 1024 / 1024 +}