-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmemorylimit.go
More file actions
226 lines (193 loc) · 4.81 KB
/
memorylimit.go
File metadata and controls
226 lines (193 loc) · 4.81 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package pipe
import (
"context"
"errors"
"fmt"
"io"
"sync"
"time"
)
const memoryPollInterval = time.Second
// ErrMemoryLimitExceeded is the error that will be used to kill a
// process, if necessary, from MemoryLimit.
var ErrMemoryLimitExceeded = errors.New("memory limit exceeded")
// LimitableStage is the superset of `Stage` that must be implemented
// by stages passed to MemoryLimit and MemoryObserver.
type LimitableStage interface {
Stage
GetRSSAnon(context.Context) (uint64, error)
Kill(error)
}
// MemoryLimit watches the memory usage of the stage and stops it if it
// exceeds the given limit.
func MemoryLimit(stage Stage, byteLimit uint64, eventHandler func(e *Event)) Stage {
limitableStage, ok := stage.(LimitableStage)
if !ok {
eventHandler(&Event{
Command: stage.Name(),
Msg: "invalid pipe.MemoryLimit usage",
Err: fmt.Errorf("invalid pipe.MemoryLimit usage"),
})
return stage
}
return &memoryWatchStage{
nameSuffix: " with memory limit",
stage: limitableStage,
watch: killAtLimit(byteLimit, eventHandler),
}
}
func killAtLimit(byteLimit uint64, eventHandler func(e *Event)) memoryWatchFunc {
return func(ctx context.Context, stage LimitableStage) {
var consecutiveErrors int
t := time.NewTicker(memoryPollInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
rss, err := stage.GetRSSAnon(ctx)
if err != nil {
consecutiveErrors++
if consecutiveErrors >= 2 {
eventHandler(&Event{
Command: stage.Name(),
Msg: "error getting RSS",
Err: err,
})
}
continue
}
consecutiveErrors = 0
if rss < byteLimit {
continue
}
eventHandler(&Event{
Command: stage.Name(),
Msg: "stage exceeded allowed memory use",
Err: fmt.Errorf("stage exceeded allowed memory use"),
Context: map[string]interface{}{
"limit": byteLimit,
"used": rss,
},
})
stage.Kill(ErrMemoryLimitExceeded)
return
}
}
}
}
// MemoryObserver watches memory use of the stage and logs the maximum
// value when the stage exits.
func MemoryObserver(stage Stage, eventHandler func(e *Event)) Stage {
limitableStage, ok := stage.(LimitableStage)
if !ok {
eventHandler(&Event{
Command: stage.Name(),
Msg: "invalid pipe.MemoryObserver usage",
Err: fmt.Errorf("invalid pipe.MemoryObserver usage"),
})
return stage
}
return &memoryWatchStage{
stage: limitableStage,
watch: logMaxRSS(eventHandler),
}
}
func logMaxRSS(eventHandler func(e *Event)) memoryWatchFunc {
return func(ctx context.Context, stage LimitableStage) {
var (
maxRSS uint64
samples, errors, consecutiveErrors int
)
t := time.NewTicker(memoryPollInterval)
defer t.Stop()
for {
select {
case <-ctx.Done():
eventHandler(&Event{
Command: stage.Name(),
Msg: "peak memory usage",
Context: map[string]interface{}{
"max_rss_bytes": maxRSS,
"samples": samples,
"errors": errors,
},
})
return
case <-t.C:
rss, err := stage.GetRSSAnon(ctx)
if err != nil {
errors++
consecutiveErrors++
if consecutiveErrors == 2 {
eventHandler(&Event{
Command: stage.Name(),
Msg: "error getting RSS",
Err: err,
})
}
// don't log any more errors until we get rss successfully.
continue
}
consecutiveErrors = 0
samples++
if rss > maxRSS {
maxRSS = rss
}
}
}
}
}
type memoryWatchStage struct {
nameSuffix string
stage LimitableStage
watch memoryWatchFunc
cancel context.CancelFunc
wg sync.WaitGroup
}
type memoryWatchFunc func(context.Context, LimitableStage)
var _ LimitableStage = (*memoryWatchStage)(nil)
func (m *memoryWatchStage) Name() string {
return m.stage.Name() + m.nameSuffix
}
func (m *memoryWatchStage) Preferences() StagePreferences {
return m.stage.Preferences()
}
func (m *memoryWatchStage) Start(
ctx context.Context, env Env, stdin io.ReadCloser, stdout io.WriteCloser,
) error {
if err := m.stage.Start(ctx, env, stdin, stdout); err != nil {
return err
}
m.monitor(ctx)
return nil
}
// monitor starts up a goroutine that monitors the memory of `m`.
func (m *memoryWatchStage) monitor(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
m.cancel = cancel
m.wg.Add(1)
go func() {
m.watch(ctx, m.stage)
m.wg.Done()
}()
}
func (m *memoryWatchStage) Wait() error {
if err := m.stage.Wait(); err != nil {
return err
}
m.stopWatching()
return nil
}
func (m *memoryWatchStage) GetRSSAnon(ctx context.Context) (uint64, error) {
return m.stage.GetRSSAnon(ctx)
}
func (m *memoryWatchStage) Kill(err error) {
m.stage.Kill(err)
m.stopWatching()
}
func (m *memoryWatchStage) stopWatching() {
m.cancel()
m.wg.Wait()
}