-
Notifications
You must be signed in to change notification settings - Fork 491
/
autoscale.go
627 lines (543 loc) · 14.8 KB
/
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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package kapacitor
import (
"fmt"
"time"
"github.com/influxdata/kapacitor/edge"
"github.com/influxdata/kapacitor/expvar"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
ec2 "github.com/influxdata/kapacitor/services/ec2/client"
k8s "github.com/influxdata/kapacitor/services/k8s/client"
swarm "github.com/influxdata/kapacitor/services/swarm/client"
"github.com/influxdata/kapacitor/tick/ast"
"github.com/influxdata/kapacitor/tick/stateful"
"github.com/pkg/errors"
)
const (
statsAutoscaleIncreaseEventsCount = "increase_events"
statsAutoscaleDecreaseEventsCount = "decrease_events"
statsAutoscaleCooldownDropsCount = "cooldown_drops"
)
type resourceID interface {
ID() string
}
type autoscaler interface {
ResourceIDFromTags(models.Tags) (resourceID, error)
Replicas(id resourceID) (int, error)
SetReplicas(id resourceID, replicas int) error
SetResourceIDOnTags(id resourceID, tags models.Tags)
}
type resourceState struct {
lastIncrease time.Time
lastDecrease time.Time
current int
}
type event struct {
ID resourceID
Old int
New int
}
type AutoscaleNode struct {
node
a autoscaler
replicasExpr stateful.Expression
replicasScopePool stateful.ScopePool
resourceStates map[string]resourceState
increaseCount *expvar.Int
decreaseCount *expvar.Int
cooldownDropsCount *expvar.Int
min int
max int
increaseCooldown time.Duration
decreaseCooldown time.Duration
currentField string
}
// Create a new AutoscaleNode which can trigger autoscale events.
func newAutoscaleNode(
et *ExecutingTask,
d NodeDiagnostic,
n pipeline.Node,
a autoscaler,
min,
max int,
increaseCooldown,
decreaseCooldown time.Duration,
currentField string,
replicas *ast.LambdaNode,
) (*AutoscaleNode, error) {
if min < 1 {
return nil, fmt.Errorf("minimum count must be >= 1, got %d", min)
}
// Initialize the replicas lambda expression scope pool
replicasExpr, err := stateful.NewExpression(replicas.Expression)
if err != nil {
return nil, errors.Wrap(err, "invalid replicas expression")
}
replicasScopePool := stateful.NewScopePool(ast.FindReferenceVariables(replicas.Expression))
kn := &AutoscaleNode{
node: node{Node: n, et: et, diag: d},
resourceStates: make(map[string]resourceState),
min: min,
max: max,
increaseCooldown: increaseCooldown,
decreaseCooldown: decreaseCooldown,
currentField: currentField,
a: a,
replicasExpr: replicasExpr,
replicasScopePool: replicasScopePool,
}
kn.node.runF = kn.runAutoscale
return kn, nil
}
func (n *AutoscaleNode) runAutoscale([]byte) error {
n.increaseCount = &expvar.Int{}
n.decreaseCount = &expvar.Int{}
n.cooldownDropsCount = &expvar.Int{}
n.statMap.Set(statsAutoscaleIncreaseEventsCount, n.increaseCount)
n.statMap.Set(statsAutoscaleDecreaseEventsCount, n.decreaseCount)
n.statMap.Set(statsAutoscaleCooldownDropsCount, n.cooldownDropsCount)
consumer := edge.NewGroupedConsumer(
n.ins[0],
n,
)
n.statMap.Set(statCardinalityGauge, consumer.CardinalityVar())
return consumer.Consume()
}
func (n *AutoscaleNode) NewGroup(group edge.GroupInfo, first edge.PointMeta) (edge.Receiver, error) {
return edge.NewReceiverFromForwardReceiverWithStats(
n.outs,
edge.NewTimedForwardReceiver(n.timer, n.newGroup()),
), nil
}
func (n *AutoscaleNode) newGroup() *autoscaleGroup {
return &autoscaleGroup{
n: n,
expr: n.replicasExpr.CopyReset(),
}
}
type autoscaleGroup struct {
n *AutoscaleNode
expr stateful.Expression
begin edge.BeginBatchMessage
}
func (g *autoscaleGroup) BeginBatch(begin edge.BeginBatchMessage) (edge.Message, error) {
g.begin = begin
return nil, nil
}
func (g *autoscaleGroup) BatchPoint(bp edge.BatchPointMessage) (edge.Message, error) {
np, err := g.n.handlePoint(g.begin.Name(), g.begin.Dimensions(), bp, g.expr)
if err != nil {
g.n.diag.Error("error batch handling point", err)
}
return np, nil
}
func (g *autoscaleGroup) EndBatch(end edge.EndBatchMessage) (edge.Message, error) {
return nil, nil
}
func (g *autoscaleGroup) Point(p edge.PointMessage) (edge.Message, error) {
np, err := g.n.handlePoint(p.Name(), p.Dimensions(), p, g.expr)
if err != nil {
g.n.diag.Error("error handling point", err)
}
return np, nil
}
func (g *autoscaleGroup) Barrier(b edge.BarrierMessage) (edge.Message, error) {
return b, nil
}
func (g *autoscaleGroup) DeleteGroup(d edge.DeleteGroupMessage) (edge.Message, error) {
return d, nil
}
func (g *autoscaleGroup) Done() {}
func (n *AutoscaleNode) handlePoint(streamName string, dims models.Dimensions, p edge.FieldsTagsTimeGetter, expr stateful.Expression) (edge.PointMessage, error) {
id, err := n.a.ResourceIDFromTags(p.Tags())
if err != nil {
return nil, err
}
state, ok := n.resourceStates[id.ID()]
if !ok {
// If we haven't seen this resource before, get its state
replicas, err := n.a.Replicas(id)
if err != nil {
return nil, errors.Wrapf(err, "could not determine initial scale for %q", id)
}
state = resourceState{
current: replicas,
}
n.resourceStates[id.ID()] = state
}
// Eval the replicas expression
newReplicas, err := n.evalExpr(state.current, expr, p)
if err != nil {
return nil, errors.Wrap(err, "failed to evaluate the replicas expression")
}
// Create the event
e := event{
ID: id,
Old: state.current,
New: newReplicas,
}
// Check bounds
if n.max > 0 && e.New > n.max {
e.New = n.max
}
if e.New < n.min {
e.New = n.min
}
// Validate something changed
if e.New == e.Old {
// Nothing to do
return nil, nil
}
// Update local copy of state
change := e.New - e.Old
state.current = e.New
// Check last change cooldown times
t := p.Time()
var counter *expvar.Int
switch {
case change > 0:
if t.Before(state.lastIncrease.Add(n.increaseCooldown)) {
// Still hot, nothing to do
n.cooldownDropsCount.Add(1)
return nil, nil
}
state.lastIncrease = t
counter = n.increaseCount
case change < 0:
if t.Before(state.lastDecrease.Add(n.decreaseCooldown)) {
// Still hot, nothing to do
n.cooldownDropsCount.Add(1)
return nil, nil
}
state.lastDecrease = t
counter = n.decreaseCount
}
// We have a valid event to apply
if err := n.applyEvent(e); err != nil {
return nil, errors.Wrap(err, "failed to apply scaling event")
}
// Only save the updated state if we were successful
n.resourceStates[id.ID()] = 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(dims.TagNames)+3)
// Copy group by tags
for _, d := range dims.TagNames {
newTags[d] = p.Tags()[d]
}
n.a.SetResourceIDOnTags(id, newTags)
// Create point representing the event
return edge.NewPointMessage(
streamName, "", "",
dims,
models.Fields{
"old": int64(e.Old),
"new": int64(e.New),
},
newTags,
t,
), nil
}
func (n *AutoscaleNode) applyEvent(e event) error {
n.diag.SettingReplicas(e.New, e.Old, e.ID.ID())
err := n.a.SetReplicas(e.ID, e.New)
return errors.Wrapf(err, "failed to set new replica count for %q", e.ID)
}
func (n *AutoscaleNode) evalExpr(
current int,
expr stateful.Expression,
p edge.FieldsTagsTimeGetter,
) (int, error) {
vars := n.replicasScopePool.Get()
defer n.replicasScopePool.Put(vars)
// Set the current replicas value on the scope if requested.
if n.currentField != "" {
vars.Set(n.currentField, current)
}
// Fill the scope with the rest of the values
err := fillScope(vars, n.replicasScopePool.ReferenceVariables(), p)
if err != nil {
return 0, err
}
i, err := expr.EvalInt(vars)
if err != nil {
return 0, err
}
return int(i), err
}
////////////////////////////////////
// K8s implementation of Autoscaler
type k8sAutoscaler struct {
client k8s.Client
resourceName string
resourceNameTag string
namespaceTag string
kindTag string
nameTag string
kind string
namespace string
}
func newK8sAutoscaleNode(et *ExecutingTask, n *pipeline.K8sAutoscaleNode, d NodeDiagnostic) (*AutoscaleNode, error) {
client, err := et.tm.K8sService.Client(n.Cluster)
if err != nil {
return nil, fmt.Errorf("cannot use the k8sAutoscale node, could not create kubernetes client: %v", err)
}
a := &k8sAutoscaler{
client: client,
resourceName: n.ResourceName,
resourceNameTag: n.ResourceNameTag,
namespaceTag: n.NamespaceTag,
kindTag: n.KindTag,
nameTag: n.ResourceTag,
kind: n.Kind,
namespace: n.Namespace,
}
return newAutoscaleNode(
et,
d,
n,
a,
int(n.Min),
int(n.Max),
n.IncreaseCooldown,
n.DecreaseCooldown,
n.CurrentField,
n.Replicas,
)
}
type k8sResourceID struct {
Namespace,
Kind,
Name string
}
func (id k8sResourceID) ID() string {
return id.Name
}
func (id k8sResourceID) String() string {
return fmt.Sprintf("%s/%s/%s", id.Namespace, id.Kind, id.Name)
}
func (a *k8sAutoscaler) ResourceIDFromTags(tags models.Tags) (resourceID, error) {
// Get the name of the resource
var name string
switch {
case a.resourceName != "":
name = a.resourceName
case a.resourceNameTag != "":
t, ok := tags[a.resourceNameTag]
if ok {
name = t
}
default:
return nil, errors.New("expected one of ResourceName or ResourceNameTag to be set")
}
if name == "" {
return nil, errors.New("could not determine the name of the resource")
}
namespace := a.namespace
if namespace == "" {
namespace = k8s.NamespaceDefault
}
return k8sResourceID{
Namespace: namespace,
Kind: a.kind,
Name: name,
}, nil
}
func (a *k8sAutoscaler) getScale(kid k8sResourceID) (*k8s.Scale, error) {
scales := a.client.Scales(kid.Namespace)
scale, err := scales.Get(kid.Kind, kid.Name)
return scale, err
}
func (a *k8sAutoscaler) Replicas(id resourceID) (int, error) {
kid := id.(k8sResourceID)
scale, err := a.getScale(kid)
if err != nil {
return 0, err
}
return int(scale.Spec.Replicas), nil
}
func (a *k8sAutoscaler) SetReplicas(id resourceID, replicas int) error {
kid := id.(k8sResourceID)
scale, err := a.getScale(kid)
if err != nil {
return err
}
scale.Spec.Replicas = int32(replicas)
scales := a.client.Scales(kid.Namespace)
if err := scales.Update(kid.Kind, scale); err != nil {
return err
}
return nil
}
func (a *k8sAutoscaler) SetResourceIDOnTags(id resourceID, tags models.Tags) {
kid := id.(k8sResourceID)
// Set namespace,kind,resource tags
if a.namespaceTag != "" {
tags[a.namespaceTag] = kid.Namespace
}
if a.kindTag != "" {
tags[a.kindTag] = kid.Kind
}
if a.nameTag != "" {
tags[a.nameTag] = kid.Name
}
}
/////////////////////////////////////////////
// Docker Swarm implementation of Autoscaler
type swarmAutoscaler struct {
client swarm.Client
serviceName string
serviceNameTag string
outputServiceNameTag string
}
func newSwarmAutoscaleNode(et *ExecutingTask, n *pipeline.SwarmAutoscaleNode, d NodeDiagnostic) (*AutoscaleNode, error) {
client, err := et.tm.SwarmService.Client(n.Cluster)
if err != nil {
return nil, fmt.Errorf("cannot use the swarmAutoscale node, could not create swarm client: %v", err)
}
outputServiceNameTag := n.OutputServiceNameTag
if outputServiceNameTag == "" {
outputServiceNameTag = n.ServiceNameTag
}
a := &swarmAutoscaler{
client: client,
serviceName: n.ServiceName,
serviceNameTag: n.ServiceNameTag,
outputServiceNameTag: outputServiceNameTag,
}
return newAutoscaleNode(
et,
d,
n,
a,
int(n.Min),
int(n.Max),
n.IncreaseCooldown,
n.DecreaseCooldown,
n.CurrentField,
n.Replicas,
)
}
type swarmResourceID string
func (id swarmResourceID) ID() string {
return string(id)
}
func (a *swarmAutoscaler) ResourceIDFromTags(tags models.Tags) (resourceID, error) {
// Get the name of the resource
var name string
switch {
case a.serviceName != "":
name = a.serviceName
case a.serviceNameTag != "":
t, ok := tags[a.serviceNameTag]
if ok {
name = t
}
default:
return nil, errors.New("expected one of ServiceName or ServiceNameTag to be set")
}
if name == "" {
return nil, errors.New("could not determine the name of the resource")
}
return swarmResourceID(name), nil
}
func (a *swarmAutoscaler) Replicas(id resourceID) (int, error) {
sid := id.ID()
service, err := a.client.Service(sid)
if err != nil {
return 0, errors.Wrapf(err, "failed to get swarm service for %q", id)
}
return int(*service.Spec.Mode.Replicated.Replicas), nil
}
func (a *swarmAutoscaler) SetReplicas(id resourceID, replicas int) error {
sid := id.ID()
service, err := a.client.Service(sid)
if err != nil {
return errors.Wrapf(err, "failed to get swarm service for %q", id)
}
*service.Spec.Mode.Replicated.Replicas = uint64(replicas)
return a.client.UpdateService(service)
}
func (a *swarmAutoscaler) SetResourceIDOnTags(id resourceID, tags models.Tags) {
if a.outputServiceNameTag != "" {
tags[a.outputServiceNameTag] = id.ID()
}
}
/////////////////////////////////////////////
// EC2 implementation of Autoscaler
type ec2Autoscaler struct {
client ec2.Client
groupName string
groupNameTag string
outputGroupNameTag string
}
func newEc2AutoscaleNode(et *ExecutingTask, n *pipeline.Ec2AutoscaleNode, d NodeDiagnostic) (*AutoscaleNode, error) {
client, err := et.tm.EC2Service.Client(n.Cluster)
if err != nil {
return nil, fmt.Errorf("cannot use the EC2Autoscale node, could not create ec2 client: %v", err)
}
outputGroupNameTag := n.OutputGroupNameTag
if outputGroupNameTag == "" {
outputGroupNameTag = n.GroupNameTag
}
a := &ec2Autoscaler{
client: client,
groupName: n.GroupName,
groupNameTag: n.GroupNameTag,
outputGroupNameTag: outputGroupNameTag,
}
return newAutoscaleNode(
et,
d,
n,
a,
int(n.Min),
int(n.Max),
n.IncreaseCooldown,
n.DecreaseCooldown,
n.CurrentField,
n.Replicas,
)
}
func (a *ec2Autoscaler) ResourceIDFromTags(tags models.Tags) (resourceID, error) {
// Get the name of the resource
var name string
switch {
case a.groupName != "":
name = a.groupName
case a.groupNameTag != "":
t, ok := tags[a.groupNameTag]
if ok {
name = t
}
default:
return nil, errors.New("expected one of GroupName or GroupNameTag to be set")
}
if name == "" {
return nil, errors.New("could not determine the name of the resource")
}
return swarmResourceID(name), nil
}
func (a *ec2Autoscaler) Replicas(id resourceID) (int, error) {
sid := id.ID()
group, err := a.client.Group(sid)
if err != nil {
return 0, errors.Wrapf(err, "failed to get ec2 autoscaleGroup for %q", id)
}
var desiredcapacity int64
for _, resp := range group.AutoScalingGroups {
desiredcapacity = *resp.DesiredCapacity
}
return int(desiredcapacity), nil
}
func (a *ec2Autoscaler) SetReplicas(id resourceID, replicas int) error {
sid := id.ID()
return a.client.UpdateGroup(sid, int64(replicas))
}
func (a *ec2Autoscaler) SetResourceIDOnTags(id resourceID, tags models.Tags) {
if a.outputGroupNameTag != "" {
tags[a.outputGroupNameTag] = id.ID()
}
}