forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s_autoscale.go
344 lines (308 loc) · 9.24 KB
/
k8s_autoscale.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
package kapacitor
import (
"fmt"
"log"
"time"
"github.com/influxdata/kapacitor/expvar"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
"github.com/influxdata/kapacitor/services/k8s/client"
"github.com/influxdata/kapacitor/tick/ast"
"github.com/influxdata/kapacitor/tick/stateful"
"github.com/pkg/errors"
)
const (
statsK8sIncreaseEventsCount = "increase_events"
statsK8sDecreaseEventsCount = "decrease_events"
statsK8sErrorsCount = "errors"
statsK8sCooldownDropsCount = "cooldown_drops"
)
type K8sAutoscaleNode struct {
node
k *pipeline.K8sAutoscaleNode
client client.Client
replicasExprs map[models.GroupID]stateful.Expression
replicasScopePool stateful.ScopePool
resourceStates map[string]resourceState
increaseCount *expvar.Int
decreaseCount *expvar.Int
cooldownDropsCount *expvar.Int
min int
max int
}
// Create a new K8sAutoscaleNode which can trigger autoscale event for a Kubernetes cluster.
func newK8sAutoscaleNode(et *ExecutingTask, n *pipeline.K8sAutoscaleNode, l *log.Logger) (*K8sAutoscaleNode, error) {
client, err := et.tm.K8sService.Client()
if err != nil {
return nil, fmt.Errorf("cannot use the k8sAutoscale node, could not create kubernetes client: %v", err)
}
kn := &K8sAutoscaleNode{
node: node{Node: n, et: et, logger: l},
k: n,
resourceStates: make(map[string]resourceState),
min: int(n.Min),
max: int(n.Max),
client: client,
}
if kn.min < 1 {
return nil, fmt.Errorf("minimum count must be >= 1, got %d", kn.min)
}
kn.node.runF = kn.runAutoscale
// Initialize the replicas lambda expression scope pool
if n.Replicas != nil {
kn.replicasExprs = make(map[models.GroupID]stateful.Expression)
kn.replicasScopePool = stateful.NewScopePool(stateful.FindReferenceVariables(n.Replicas.Expression))
}
return kn, nil
}
func (k *K8sAutoscaleNode) runAutoscale([]byte) error {
k.increaseCount = &expvar.Int{}
k.decreaseCount = &expvar.Int{}
errorsCount := &expvar.Int{}
k.cooldownDropsCount = &expvar.Int{}
k.statMap.Set(statsK8sIncreaseEventsCount, k.increaseCount)
k.statMap.Set(statsK8sDecreaseEventsCount, k.decreaseCount)
k.statMap.Set(statsK8sErrorsCount, errorsCount)
k.statMap.Set(statsK8sCooldownDropsCount, k.cooldownDropsCount)
switch k.Wants() {
case pipeline.StreamEdge:
for p, ok := k.ins[0].NextPoint(); ok; p, ok = k.ins[0].NextPoint() {
k.timer.Start()
if np, err := k.handlePoint(p.Name, p.Group, p.Dimensions, p.Time, p.Fields, p.Tags); err != nil {
errorsCount.Add(1)
k.logger.Println("E!", err)
} else if np.Name != "" {
k.timer.Pause()
for _, child := range k.outs {
err := child.CollectPoint(np)
if err != nil {
return err
}
}
k.timer.Resume()
}
k.timer.Stop()
}
case pipeline.BatchEdge:
for b, ok := k.ins[0].NextBatch(); ok; b, ok = k.ins[0].NextBatch() {
k.timer.Start()
for _, p := range b.Points {
if np, err := k.handlePoint(b.Name, b.Group, b.PointDimensions(), p.Time, p.Fields, p.Tags); err != nil {
errorsCount.Add(1)
k.logger.Println("E!", err)
} else if np.Name != "" {
k.timer.Pause()
for _, child := range k.outs {
err := child.CollectPoint(np)
if err != nil {
return err
}
}
k.timer.Resume()
}
}
k.timer.Stop()
}
}
return nil
}
type resourceState struct {
lastIncrease time.Time
lastDecrease time.Time
current int
}
type event struct {
Namespace string
Kind string
Name string
Old int
New int
}
func (k *K8sAutoscaleNode) handlePoint(streamName string, group models.GroupID, dims models.Dimensions, t time.Time, fields models.Fields, tags models.Tags) (models.Point, error) {
namespace, kind, name, err := k.getResourceFromPoint(tags)
if err != nil {
return models.Point{}, err
}
state, ok := k.resourceStates[name]
if !ok {
// If we haven't seen this resource before, get its state
scale, err := k.getResource(namespace, kind, name)
if err != nil {
return models.Point{}, errors.Wrapf(err, "could not determine initial scale for %s/%s/%s", namespace, kind, name)
}
state.current = int(scale.Spec.Replicas)
k.resourceStates[name] = state
}
// Eval the replicas expression
newReplicas, err := k.evalExpr(state.current, group, k.k.Replicas, k.replicasExprs, k.replicasScopePool, t, fields, tags)
if err != nil {
return models.Point{}, errors.Wrap(err, "failed to evaluate the replicas expression")
}
// Create the event
e := event{
Namespace: namespace,
Kind: kind,
Name: name,
Old: state.current,
New: newReplicas,
}
// Check bounds
if k.max > 0 && e.New > k.max {
e.New = k.max
}
if e.New < k.min {
e.New = k.min
}
// Validate something changed
if e.New == e.Old {
// Nothing to do
return models.Point{}, nil
}
// Update local copy of state
change := e.New - e.Old
state.current = e.New
// Check last change cooldown times
var counter *expvar.Int
switch {
case change > 0:
if t.Before(state.lastIncrease.Add(k.k.IncreaseCooldown)) {
// Still hot, nothing to do
k.cooldownDropsCount.Add(1)
return models.Point{}, nil
}
state.lastIncrease = t
counter = k.increaseCount
case change < 0:
if t.Before(state.lastDecrease.Add(k.k.DecreaseCooldown)) {
// Still hot, nothing to do
k.cooldownDropsCount.Add(1)
return models.Point{}, nil
}
state.lastDecrease = t
counter = k.decreaseCount
}
// We have a valid event to apply
if err := k.applyEvent(e); err != nil {
return models.Point{}, errors.Wrap(err, "failed to apply scaling event")
}
// Only save the updated state if we were successful
k.resourceStates[name] = state
// Count event
counter.Add(1)
// Create new tags for the point.
// Leave room for the namespace,kind, and resource tags.
newTags := make(models.Tags, len(tags)+3)
// Copy group by tags
for _, d := range dims.TagNames {
newTags[d] = tags[d]
}
// Set namespace,kind,resource tags
if k.k.NamespaceTag != "" {
newTags[k.k.NamespaceTag] = namespace
}
if k.k.KindTag != "" {
newTags[k.k.KindTag] = kind
}
if k.k.ResourceTag != "" {
newTags[k.k.ResourceTag] = name
}
// Create point representing the event
p := models.Point{
Name: streamName,
Time: t,
Group: group,
Dimensions: dims,
Tags: newTags,
Fields: models.Fields{
"old": int64(e.Old),
"new": int64(e.New),
},
}
return p, nil
}
func (k *K8sAutoscaleNode) getResourceFromPoint(tags models.Tags) (namespace, kind, name string, err error) {
// Get the name of the resource
switch {
case k.k.ResourceName != "":
name = k.k.ResourceName
case k.k.ResourceNameTag != "":
t, ok := tags[k.k.ResourceNameTag]
if ok {
name = t
}
default:
return "", "", "", errors.New("expected one of ResourceName, ResourceNameField and ResourceNameTag to be set")
}
if name == "" {
return "", "", "", errors.New("could not determine the name of the resource")
}
namespace = k.k.Namespace
if namespace == "" {
namespace = client.NamespaceDefault
}
kind = k.k.Kind
return
}
func (k *K8sAutoscaleNode) getResource(namespace, kind, name string) (*client.Scale, error) {
scales := k.client.Scales(namespace)
scale, err := scales.Get(kind, name)
return scale, errors.Wrapf(err, "failed to get the scale for resource %s/%s/%s", namespace, kind, name)
}
func (k *K8sAutoscaleNode) applyEvent(e event) error {
k.logger.Printf("D! setting scale replicas to %d was %d for %s/%s/%s", e.New, e.Old, e.Namespace, e.Kind, e.Name)
scales := k.client.Scales(e.Namespace)
scale, err := k.getResource(e.Namespace, e.Kind, e.Name)
if err != nil {
return err
}
if scale.Spec.Replicas != int32(e.Old) {
k.logger.Printf("W! the kubernetes scale spec and Kapacitor's spec do not match for resource %s/%s/%s, did it change externally?", e.Namespace, e.Kind, e.Name)
}
scale.Spec.Replicas = int32(e.New)
if err := scales.Update(e.Kind, scale); err != nil {
return errors.Wrapf(err, "failed to update the scale for resource %s/%s/%s", e.Namespace, e.Kind, e.Name)
}
return nil
}
func (k *K8sAutoscaleNode) evalExpr(
current int,
group models.GroupID,
lambda *ast.LambdaNode,
expressionsMap map[models.GroupID]stateful.Expression,
pool stateful.ScopePool,
t time.Time,
fields models.Fields,
tags models.Tags,
) (int, error) {
expr, ok := expressionsMap[group]
if !ok {
var err error
expr, err = stateful.NewExpression(lambda.Expression)
if err != nil {
return 0, err
}
expressionsMap[group] = expr
}
i, err := k.evalInt(int64(current), expr, pool, t, fields, tags)
return int(i), err
}
// evalInt - Evaluate a given expression as an int64 against a set of fields and tags.
// The CurrentField is also set on the scope if not empty.
func (k *K8sAutoscaleNode) evalInt(current int64, se stateful.Expression, scopePool stateful.ScopePool, now time.Time, fields models.Fields, tags models.Tags) (int64, error) {
vars := scopePool.Get()
defer scopePool.Put(vars)
// Set the current replicas value on the scope if requested.
if k.k.CurrentField != "" {
vars.Set(k.k.CurrentField, current)
}
// Fill the scope with the rest of the values
err := fillScope(vars, scopePool.ReferenceVariables(), now, fields, tags)
if err != nil {
return 0, err
}
i, err := se.EvalInt(vars)
if err != nil {
return 0, err
}
return i, nil
}