-
Notifications
You must be signed in to change notification settings - Fork 0
/
limit.go
76 lines (59 loc) · 1.28 KB
/
limit.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
package limit
import (
"context"
"errors"
"fmt"
"log"
"runtime"
"time"
)
type MemLimit struct {
ctx context.Context
maxMemory uint64
onLimit func(string)
}
func WithResourcesLimit(parent context.Context, maxTime time.Duration, maxMem uint64, block func(context.Context)) {
ctx, cancel := context.WithTimeout(parent, maxTime)
defer cancel()
memLimit := &MemLimit{
ctx: ctx,
maxMemory: maxMem,
onLimit: func(msg string) { log.Fatal(msg) },
}
memLimit.Execute(block)
}
func (m *MemLimit) Execute(block func(context.Context)) error {
exceeded := make(chan uint64)
done := make(chan bool)
go m.sampling(exceeded)
go m.run(done, block)
select {
case <-done:
return nil
case <-m.ctx.Done():
m.onLimit("context done")
case bytes := <-exceeded:
m.onLimit(fmt.Sprintf("memory limit exceeded, allocated %d bytes", bytes))
}
return errors.New("limits reached")
}
func (m *MemLimit) sampling(exceeded chan<- uint64) {
var s runtime.MemStats
for {
if m.ctx.Err() != nil {
break
}
runtime.ReadMemStats(&s)
if s.HeapAlloc > m.maxMemory {
exceeded <- s.HeapAlloc
}
time.Sleep(time.Millisecond)
}
}
func (m *MemLimit) run(done chan<- bool, block func(context.Context)) {
if m.ctx.Err() != nil {
return
}
block(m.ctx)
close(done)
}