-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemwatch.go
105 lines (90 loc) · 2.27 KB
/
memwatch.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package heatmap
import (
"fmt"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
type memWatch struct {
ramDatastore *ramDatastore
config *config
memThreshold uint64 // in bytes
gcChan chan struct{}
}
var multipliers = map[string]uint64{
"bytes": 1,
"b": 1,
"kb": 1024,
"mb": 1024 * 1024,
"gb": 1024 * 1024 * 1024,
"tb": 1024 * 1024 * 1024 * 1024,
"pb": 1024 * 1024 * 1024 * 1024 * 1024,
}
func (m *memWatch) scheduleGCRun() {
logDebug.Printf("[MEMWATCH] scheduling a GC run")
select {
case m.gcChan <- struct{}{}:
default:
}
}
func (m *memWatch) gcSubroutine() {
for {
<-m.gcChan
reportTime("GC run", func() { runtime.GC() })
}
}
func (m *memWatch) start() {
m.gcChan = make(chan struct{}, 1)
go m.gcSubroutine()
t := time.NewTicker(time.Second)
if strings.Contains(m.config.memThreshold, "%") {
percentage, err := strconv.ParseFloat(strings.Replace(m.config.memThreshold, "%", "", 1), 64)
if err != nil {
panic(err)
}
m.memThreshold = uint64(percentage / 100.0 * float64(memoryTotal()))
} else {
re := regexp.MustCompile("(\\d*\\.?\\d*)\\s*(\\S+)")
submatches := re.FindStringSubmatch(m.config.memThreshold)
if len(submatches) < 3 {
panic(fmt.Sprintf("could not parse mem-threshold %s", m.config.memThreshold))
}
value, err := strconv.ParseFloat(submatches[1], 64)
if err != nil {
panic(err)
}
multiplier := strings.ToLower(submatches[2])
if multiplierUint, ok := multipliers[multiplier]; ok {
m.memThreshold = uint64(value * float64(multiplierUint))
} else {
panic(fmt.Sprintf("could not parse mem-threshold, unknown multipler %s", multiplier))
}
}
for {
<-t.C
used := memoryUsed()
logDebug.Printf("[MEMWATCH] checking on memory usage %d/%d", used, m.memThreshold)
if used > m.memThreshold {
m.scheduleGCRun()
}
time.Sleep(time.Second)
used = memoryUsed()
if used > m.memThreshold {
logDebug.Printf("[MEMWATCH] doing a full cleanup")
reportTime("RAM datastore cleanup", func() { m.ramDatastore.cleanup() })
m.scheduleGCRun()
}
}
}
func memoryUsed() uint64 {
var m runtime.MemStats
runtime.ReadMemStats(&m)
return m.Alloc
}
func reportTime(label string, cb func()) {
t := time.Now()
cb()
logDebug.Printf("[MEMWATCH] %s took %s", label, time.Now().Sub(t).String())
}