-
Notifications
You must be signed in to change notification settings - Fork 927
/
memwatcher.go
57 lines (46 loc) · 1.19 KB
/
memwatcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package bot
import (
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/config"
"runtime/debug"
"time"
"github.com/shirou/gopsutil/mem"
)
const MemFreeThreshold = 90
type MemWatcher struct {
lastTimeFreed time.Time
}
var confEnableMemMonitor = config.RegisterOption("yagpdb.mem_monitor.enabled", "Enable the memory monitor, will attempt to free resources when os is running low", true)
var memLogger = common.GetFixedPrefixLogger("[mem_monitor]")
func watchMemusage() {
if !confEnableMemMonitor.GetBool() {
// not enabled
memLogger.Info("memory monitor disabled")
return
}
watcher := &MemWatcher{}
go watcher.Run()
}
func (mw *MemWatcher) Run() {
memLogger.Info("launching memory monitor")
ticker := time.NewTicker(time.Second * 10)
for {
<-ticker.C
mw.Check()
}
}
func (mw *MemWatcher) Check() {
if time.Since(mw.lastTimeFreed) < time.Minute*10 {
return
}
sysMem, err := mem.VirtualMemory()
if err != nil {
memLogger.WithError(err).Error("failed retrieving os memory stats")
return
}
if sysMem.UsedPercent > MemFreeThreshold {
memLogger.Info("LOW SYSTEM MEMORY, ATTEMPTING TO FREE SOME")
debug.FreeOSMemory()
mw.lastTimeFreed = time.Now()
}
}