-
Notifications
You must be signed in to change notification settings - Fork 24
/
watchdog.go
379 lines (325 loc) · 10.7 KB
/
watchdog.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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Ported from - https://github.com/raulk/go-watchdog
package watchdog
import (
"context"
"fmt"
"runtime"
"runtime/debug"
"time"
"github.com/elastic/gosigar"
"go.uber.org/fx"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
watchdogv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/watchdog/v1"
"github.com/fluxninja/aperture/v2/pkg/config"
"github.com/fluxninja/aperture/v2/pkg/jobs"
"github.com/fluxninja/aperture/v2/pkg/log"
panichandler "github.com/fluxninja/aperture/v2/pkg/panic-handler"
"github.com/fluxninja/aperture/v2/pkg/status"
watchdogconfig "github.com/fluxninja/aperture/v2/pkg/watchdog/config"
)
// swagger:operation POST /watchdog common-configuration Watchdog
// ---
// x-fn-config-env: true
// parameters:
// - name: memory
// in: body
// schema:
// "$ref": "#/definitions/WatchdogConfig"
const (
watchdogConfigKey = "watchdog.memory"
watchdogJobName = "watchdog"
)
// Module is a fx module that provides annotated Watchdog jobs and triggers Watchdog checks.
func Module() fx.Option {
return fx.Options(
fx.Invoke(Constructor{ConfigKey: watchdogConfigKey}.setupWatchdog),
)
}
// Constructor holds fields to set up the Watchdog.
type Constructor struct {
// ConfigKey for config
ConfigKey string
// Default config
DefaultConfig watchdogconfig.WatchdogConfig
}
// WatchdogIn holds parameters for setupWatchdog.
type WatchdogIn struct {
fx.In
StatusRegistry status.Registry
JobGroup *jobs.JobGroup `name:"liveness"`
Unmarshaller config.Unmarshaller
Lifecycle fx.Lifecycle
}
type watchdog struct {
sentinel *gcSentinel
heapStatusRegistry status.Registry
jobGroup *jobs.JobGroup
watchdogJob *jobs.MultiJob
config watchdogconfig.WatchdogConfig
}
func (constructor Constructor) setupWatchdog(in WatchdogIn) error {
config := constructor.DefaultConfig
if err := in.Unmarshaller.UnmarshalKey(constructor.ConfigKey, &config); err != nil {
log.Error().Err(err).Msg("Unable to deserialize watchdog policy!")
return err
}
watchdogRegistry := in.StatusRegistry.Child("system", "liveness").Child(watchdogJobName, watchdogJobName)
w := newWatchdog(in.JobGroup, watchdogRegistry, config)
in.Lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
return w.start()
},
OnStop: func(ctx context.Context) error {
return w.stop()
},
})
return nil
}
func newWatchdog(jobGroup *jobs.JobGroup, registry status.Registry, config watchdogconfig.WatchdogConfig) *watchdog {
heapStatusRegistry := registry.Child("heap", "heap")
job := jobs.NewMultiJob(jobGroup.GetStatusRegistry().Child(watchdogJobName, watchdogJobName), nil, nil)
w := &watchdog{
heapStatusRegistry: heapStatusRegistry,
jobGroup: jobGroup,
watchdogJob: job,
config: config,
sentinel: newSentinel(),
}
return w
}
func (w *watchdog) start() error {
var err error
// CGroup memory check
if runtime.GOOS == "linux" {
job := jobs.NewBasicJob("cgroup",
func(ctx context.Context) (proto.Message, error) {
return &emptypb.Empty{}, nil
})
if w.config.CGroup.WatermarksPolicy.Enabled {
cgw := &cgroupWatermarks{WatermarksPolicy: w.config.CGroup.WatermarksPolicy}
job = jobs.NewBasicJob("cgroup", cgw.Check)
} else if w.config.CGroup.AdaptivePolicy.Enabled {
cga := &cgroupAdaptive{AdaptivePolicy: w.config.CGroup.AdaptivePolicy}
job = jobs.NewBasicJob("cgroup", cga.Check)
}
err = w.watchdogJob.RegisterJob(job)
if err != nil {
return err
}
}
if w.config.System.WatermarksPolicy.Enabled || w.config.System.AdaptivePolicy.Enabled {
job := jobs.NewBasicJob("system",
func(ctx context.Context) (proto.Message, error) {
return &emptypb.Empty{}, nil
})
// System memory check
if w.config.System.WatermarksPolicy.Enabled {
sw := &systemWatermarks{WatermarksPolicy: w.config.System.WatermarksPolicy}
job = jobs.NewBasicJob("system", sw.Check)
} else if w.config.System.AdaptivePolicy.Enabled {
sa := &systemAdaptive{AdaptivePolicy: w.config.System.AdaptivePolicy}
job = jobs.NewBasicJob("system", sa.Check)
}
err = w.watchdogJob.RegisterJob(job)
if err != nil {
return err
}
}
var hp *heapPolicy
if w.config.Heap.WatermarksPolicy.Enabled || w.config.Heap.AdaptivePolicy.Enabled {
hp = newHeapPolicy(w.config.Heap)
}
// register job with job group
err = w.jobGroup.RegisterJob(w.watchdogJob, w.config.Job)
if err != nil {
return err
}
// start a go routine to track GC
panichandler.Go(func() {
for {
select {
case <-w.sentinel.gcTriggered:
log.Trace().Msg("GC detected, triggering watchdog checks")
w.jobGroup.TriggerJob(watchdogJobName, time.Duration(0))
if hp != nil {
details, e := hp.checkHeap()
if e != nil {
log.Autosample().Warn().Err(e).Msg("Heap check failed")
}
w.heapStatusRegistry.SetStatus(status.NewStatus(details, nil))
}
case <-w.sentinel.ctx.Done():
return
}
}
})
return nil
}
func (w *watchdog) stop() error {
w.sentinel.stop()
var err, merr error
err = w.jobGroup.DeregisterJob(watchdogJobName)
if err != nil {
merr = multierr.Append(merr, err)
}
_ = w.watchdogJob.DeregisterJob("cgroup")
_ = w.watchdogJob.DeregisterJob("system")
w.heapStatusRegistry.Detach()
return merr
}
// GC Sentinel trigger.
type gcSentinel struct {
gcTriggered chan struct{}
ctx context.Context
cancel context.CancelFunc
}
func newSentinel() *gcSentinel {
gcs := &gcSentinel{}
gcs.gcTriggered = make(chan struct{}, 16)
gcs.ctx, gcs.cancel = context.WithCancel(context.Background())
// this non-zero sized struct is used as a sentinel to detect when a GC
// run has finished, by setting and resetting a finalizer on it.
// it essentially creates a GC notification "flywheel"; every GC will
// trigger this finalizer, which will reset itself so it gets notified
// of the next GC, breaking the cycle when the Watchdog is stopped.
type sentinel struct{ a *int }
var finalizer func(o *sentinel)
finalizer = func(o *sentinel) {
// reset so it triggers on the next GC.
runtime.SetFinalizer(o, finalizer)
select {
case <-gcs.ctx.Done():
return
default:
}
select {
case gcs.gcTriggered <- struct{}{}:
default:
log.Warn().Msg("Failed to queue GC trigger, channel backlogged")
}
}
runtime.SetFinalizer(&sentinel{a: nil}, finalizer) // start the flywheel.
return gcs
}
func (gcs *gcSentinel) stop() {
gcs.cancel()
}
/* System policies */
func systemUsage() (uint64, uint64, error) {
var sysmem gosigar.Mem
if err := (*gosigar.Mem).Get(&sysmem); err != nil {
return 0, 0, fmt.Errorf("failed to get system memory stats: %w", err)
}
return sysmem.Total, sysmem.ActualUsed, nil
}
type systemWatermarks struct {
watchdogconfig.WatermarksPolicy
}
// Check evaluates the system memory usage and runs GC at configured watermarks of memory utilization.
func (policy *systemWatermarks) Check(ctx context.Context) (proto.Message, error) {
log.Debug().Msg("System watermarks check triggered")
msg, err := check(policy, ctx, systemUsage)
if err != nil {
log.Autosample().Warn().Err(err).Msg("System watermarks check failed")
}
return msg, nil
}
type systemAdaptive struct {
watchdogconfig.AdaptivePolicy
}
// Check evaluates the system memory usage and runs GC at configured adaptive thresholds of memory utilization.
func (policy *systemAdaptive) Check(ctx context.Context) (proto.Message, error) {
log.Debug().Msg("System adaptive check triggered")
msg, err := check(policy, ctx, systemUsage)
if err != nil {
log.Autosample().Warn().Err(err).Msg("System adaptive check failed")
}
return msg, nil
}
// Heap Policy.
type heapPolicy struct {
watchdogconfig.HeapConfig
originalGoGC int
currGoGC int
}
func newHeapPolicy(config watchdogconfig.HeapConfig) *heapPolicy {
hp := heapPolicy{HeapConfig: config}
// get the initial effective GoGC; guess it is 100 (default), and restore
// it to whatever it actually was. This works because SetGCPercent
// returns the previous value.
hp.originalGoGC = debug.SetGCPercent(100)
debug.SetGCPercent(hp.originalGoGC)
hp.currGoGC = hp.originalGoGC
// Setting go's memory limit to the configured value, changes was needed after go 1.19, limit will be respected even if gc is disabled.
debug.SetMemoryLimit(int64(config.Limit))
return &hp
}
func (hp *heapPolicy) checkHeap() (proto.Message, error) {
log.Debug().Msg("Heap check triggered")
if hp.Limit == 0 {
log.Warn().Msg("Heap limit is 0, skipping check")
return nil, nil
}
var threshold uint64
var memstats runtime.MemStats
runtime.ReadMemStats(&memstats)
// heapMarked is the amount of heap that was marked as live by GC.
// it is inferred from our current GoGC and the new target picked.
heapMarked := uint64(float64(memstats.NextGC) / (1 + float64(hp.currGoGC)/100))
usage := memstats.HeapAlloc
switch {
case hp.WatermarksPolicy.Enabled:
threshold = hp.WatermarksPolicy.NextThreshold(hp.Limit, usage)
case hp.AdaptivePolicy.Enabled:
threshold = hp.AdaptivePolicy.NextThreshold(hp.Limit, usage)
default:
log.Panic().Msg("checkHeap called on disabled policy")
}
// calculate how much to set GoGC to honor the next trigger point.
// next=PolicyTempDisabled value would make currGoGC extremely high,
// greater than originalGoGC, and therefore we'd restore originalGoGC.
hp.currGoGC = int(((float64(threshold) / float64(heapMarked)) - float64(1)) * 100)
if hp.currGoGC >= hp.originalGoGC {
hp.currGoGC = hp.originalGoGC
} else if hp.currGoGC < hp.MinGoGC {
log.Warn().Msg("heap driven watchdog reached minimum threshold for GoGC value")
// cap GoGC to avoid over scheduling.
hp.currGoGC = hp.MinGoGC
}
debug.SetGCPercent(hp.currGoGC)
runtime.ReadMemStats(&memstats)
if threshold == watchdogconfig.PolicyTempDisabled {
threshold = memstats.NextGC
}
log.Info().
Uint64("heap_alloc", memstats.HeapAlloc).
Uint64("heap_marked", heapMarked).
Uint64("memstats_nextGC", memstats.NextGC).
Uint64("threshold", threshold).
Int("current_GOGC", hp.currGoGC).
Msg("GC finished")
result := &watchdogv1.HeapResult{
Limit: hp.Limit,
HeapMarked: heapMarked,
Threshold: threshold,
CurrGogc: int32(hp.currGoGC),
OriginalGogc: int32(hp.originalGoGC),
TotalAlloc: memstats.TotalAlloc,
Sys: memstats.Sys,
Mallocs: memstats.Mallocs,
Frees: memstats.Frees,
HeapAlloc: memstats.HeapAlloc,
HeapSys: memstats.HeapSys,
HeapInuse: memstats.HeapInuse,
HeapReleased: memstats.HeapReleased,
HeapObjects: memstats.HeapObjects,
NextGc: memstats.NextGC,
LastGc: memstats.LastGC,
PauseTotalNs: memstats.PauseTotalNs,
NumGc: memstats.NumGC,
NumForcedGc: memstats.NumForcedGC,
}
return result, nil
}