forked from hashicorp/nomad
/
plan_apply_node_tracker.go
213 lines (179 loc) · 5.59 KB
/
plan_apply_node_tracker.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package nomad
import (
"fmt"
"time"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/hernad/nomad/helper"
"golang.org/x/time/rate"
)
type BadNodeTracker interface {
Add(string) bool
EmitStats(time.Duration, <-chan struct{})
}
// NoopBadNodeTracker is a no-op implementation of bad node tracker that is
// used when tracking is disabled.
type NoopBadNodeTracker struct{}
func (n *NoopBadNodeTracker) EmitStats(time.Duration, <-chan struct{}) {}
func (n *NoopBadNodeTracker) Add(string) bool {
return false
}
// CachedBadNodeTracker keeps a record of nodes marked as bad by the plan
// applier in a LRU cache.
//
// It takes a time window and a threshold value. Plan rejections for a node
// will be registered with its timestamp. If the number of rejections within
// the time window is greater than the threshold the node is reported as bad.
//
// The tracker uses a fixed size cache that evicts old entries based on access
// frequency and recency.
type CachedBadNodeTracker struct {
logger hclog.Logger
cache *lru.TwoQueueCache[string, *badNodeStats]
limiter *rate.Limiter
window time.Duration
threshold int
}
type CachedBadNodeTrackerConfig struct {
CacheSize int
RateLimit float64
BurstSize int
Window time.Duration
Threshold int
}
func DefaultCachedBadNodeTrackerConfig() CachedBadNodeTrackerConfig {
return CachedBadNodeTrackerConfig{
CacheSize: 50,
// Limit marking 5 nodes per 30min as ineligible with an initial
// burst of 10 nodes.
RateLimit: 5.0 / (30 * 60),
BurstSize: 10,
// Consider a node as bad if it is added more than 100 times in a 5min
// window period.
Window: 5 * time.Minute,
Threshold: 100,
}
}
// NewCachedBadNodeTracker returns a new CachedBadNodeTracker.
func NewCachedBadNodeTracker(logger hclog.Logger, config CachedBadNodeTrackerConfig) (*CachedBadNodeTracker, error) {
log := logger.Named("bad_node_tracker").
With("window", config.Window).
With("threshold", config.Threshold)
cache, err := lru.New2Q[string, *badNodeStats](config.CacheSize)
if err != nil {
return nil, fmt.Errorf("failed to create new bad node tracker: %v", err)
}
return &CachedBadNodeTracker{
logger: log,
cache: cache,
limiter: rate.NewLimiter(rate.Limit(config.RateLimit), config.BurstSize),
window: config.Window,
threshold: config.Threshold,
}, nil
}
// Add records a new rejection for a node and returns true if the number of
// rejections reaches the threshold.
//
// If it's the first time the node is added it will be included in the internal
// cache. If the cache is full the least recently updated or accessed node is
// evicted.
func (c *CachedBadNodeTracker) Add(nodeID string) bool {
stats, ok := c.cache.Get(nodeID)
if !ok {
stats = newBadNodeStats(nodeID, c.window)
c.cache.Add(nodeID, stats)
}
now := time.Now()
stats.record(now)
return c.isBad(now, stats)
}
// EmitStats generates metrics for the bad nodes being currently tracked. Must
// be called in a goroutine.
func (c *CachedBadNodeTracker) EmitStats(period time.Duration, stopCh <-chan struct{}) {
timer, stop := helper.NewSafeTimer(period)
defer stop()
for {
timer.Reset(period)
select {
case <-timer.C:
c.emitStats()
case <-stopCh:
return
}
}
}
// isBad returns true if the node has more rejections than the threshold within
// the time window.
func (c *CachedBadNodeTracker) isBad(t time.Time, stats *badNodeStats) bool {
score := stats.score(t)
logger := c.logger.With("node_id", stats.id, "score", score)
logger.Trace("checking if node is bad")
if score >= c.threshold {
// Limit the number of nodes we report as bad to avoid mass assigning
// nodes as ineligible, but do it after Get to keep the cache entry
// fresh.
if !c.limiter.Allow() {
logger.Trace("node is bad, but returning false due to rate limiting")
return false
}
return true
}
return false
}
func (c *CachedBadNodeTracker) emitStats() {
now := time.Now()
for _, nodeID := range c.cache.Keys() {
stats, _ := c.cache.Get(nodeID)
score := stats.score(now)
labels := []metrics.Label{
{Name: "node_id", Value: nodeID},
}
metrics.SetGaugeWithLabels([]string{"nomad", "plan", "rejection_tracker", "node_score"}, float32(score), labels)
}
}
// badNodeStats represents a node being tracked by a BadNodeTracker.
type badNodeStats struct {
id string
history []time.Time
window time.Duration
}
// newBadNodeStats returns an empty badNodeStats.
func newBadNodeStats(id string, window time.Duration) *badNodeStats {
return &badNodeStats{
id: id,
window: window,
}
}
// score returns the number of rejections within the past time window.
func (s *badNodeStats) score(t time.Time) int {
active, expired := s.countActive(t)
// Remove expired records.
if expired > 0 {
s.history = s.history[expired:]
}
return active
}
// record adds a new entry to the stats history and returns the new score.
func (s *badNodeStats) record(t time.Time) {
s.history = append(s.history, t)
}
// countActive returns the number of records that happened after the time
// window started (active) and before (expired).
func (s *badNodeStats) countActive(t time.Time) (int, int) {
windowStart := t.Add(-s.window)
// Assume all values are expired and move back from history until we find
// a record that actually happened before the window started.
expired := len(s.history)
for ; expired > 0; expired-- {
i := expired - 1
ts := s.history[i]
if ts.Before(windowStart) {
break
}
}
active := len(s.history) - expired
return active, expired
}