/
engine.go
89 lines (79 loc) · 1.97 KB
/
engine.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
package engine
import (
"context"
"github.com/Shuttl-Tech/drone-autoscaler/cluster"
"github.com/Shuttl-Tech/drone-autoscaler/config"
"github.com/drone/drone-go/drone"
log "github.com/sirupsen/logrus"
"time"
)
type droneBuildConfig struct {
pendingMaxDuration time.Duration
runningMaxDuration time.Duration
}
type droneAgentConfig struct {
maxBuilds int
minCount int
minRetirementAge time.Duration
cluster cluster.Cluster
}
type droneConfig struct {
client drone.Client
build *droneBuildConfig
agent *droneAgentConfig
}
type Engine struct {
dry bool
drone *droneConfig
probeInterval time.Duration
}
func New(c config.Config, client drone.Client, fleet cluster.Cluster) *Engine {
return &Engine{
dry: c.Dry,
drone: &droneConfig{
client: client,
build: &droneBuildConfig{
pendingMaxDuration: c.Build.PendingMaxDuration,
runningMaxDuration: c.Build.RunningMaxDuration,
},
agent: &droneAgentConfig{
cluster: fleet,
minCount: c.Agent.MinCount,
maxBuilds: c.Agent.MaxBuilds,
minRetirementAge: c.Agent.MinRetirementAge,
},
},
probeInterval: c.ProbeInterval,
}
}
func (e *Engine) Start(ctx context.Context) {
for {
select {
case <-ctx.Done():
log.Infoln("Shutting down gracefully")
return
case <-time.After(e.probeInterval):
plan, err := e.Plan(ctx)
if err != nil {
log.WithError(err).Errorln("Failed to create scaling plan")
continue
}
if e.dry {
log.
WithField("plan", plan).
Infoln("Final plan generated")
log.Infoln("Dry mode is enabled, no further action will be taken")
continue
}
if plan.RequiresUpscaling() {
if err = e.Upscale(ctx, plan.UpscaleCount()); err != nil {
log.WithError(err).Errorln("Failed to upscale")
}
} else if plan.RequiresDownscaling() {
if err = e.Downscale(ctx, plan.NodesToDestroy()); err != nil {
log.WithError(err).Errorln("Failed to downscale")
}
}
}
}
}