-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathscaler.go
289 lines (236 loc) · 7.52 KB
/
scaler.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
package scaler
import (
"log"
"math"
"time"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/buildkite/buildkite-agent-scaler/buildkite"
)
type ScaleParams struct {
Disable bool
CooldownPeriod time.Duration
Factor float64
LastEvent time.Time
}
type Params struct {
AutoScalingGroupName string
AgentsPerInstance int
BuildkiteAgentToken string
BuildkiteQueue string
UserAgent string
PublishCloudWatchMetrics bool
DryRun bool
IncludeWaiting bool
ScaleInParams ScaleParams
ScaleOutParams ScaleParams
InstanceBuffer int
ScaleOnlyAfterAllEvent bool
}
type Scaler struct {
autoscaling interface {
Describe() (AutoscaleGroupDetails, error)
SetDesiredCapacity(count int64) error
}
bk interface {
GetAgentMetrics() (buildkite.AgentMetrics, error)
}
metrics interface {
Publish(orgSlug, queue string, metrics map[string]int64) error
}
scaling ScalingCalculator
scaleInParams ScaleParams
scaleOutParams ScaleParams
instanceBuffer int
scaleOnlyAfterAllEvent bool
}
func NewScaler(client *buildkite.Client, sess *session.Session, params Params) (*Scaler, error) {
scaler := &Scaler{
bk: &buildkiteDriver{
client: client,
queue: params.BuildkiteQueue,
},
scaleInParams: params.ScaleInParams,
scaleOutParams: params.ScaleOutParams,
instanceBuffer: params.InstanceBuffer,
scaleOnlyAfterAllEvent: params.ScaleOnlyAfterAllEvent,
}
scaler.scaling = ScalingCalculator{
includeWaiting: params.IncludeWaiting,
agentsPerInstance: params.AgentsPerInstance,
}
if params.DryRun {
scaler.autoscaling = &dryRunASG{}
if params.PublishCloudWatchMetrics {
scaler.metrics = &dryRunMetricsPublisher{}
}
return scaler, nil
}
scaler.autoscaling = &ASGDriver{
Name: params.AutoScalingGroupName,
Sess: sess,
}
if params.PublishCloudWatchMetrics {
scaler.metrics = &cloudWatchMetricsPublisher{
sess: sess,
}
}
return scaler, nil
}
func (s *Scaler) Run() (time.Duration, error) {
metrics, err := s.bk.GetAgentMetrics()
if err != nil {
return metrics.PollDuration, err
}
if s.metrics != nil {
err = s.metrics.Publish(metrics.OrgSlug, metrics.Queue, map[string]int64{
"ScheduledJobsCount": metrics.ScheduledJobs,
"RunningJobsCount": metrics.RunningJobs,
"WaitingJobsCount": metrics.WaitingJobs,
})
if err != nil {
return metrics.PollDuration, err
}
}
asg, err := s.autoscaling.Describe()
if err != nil {
return metrics.PollDuration, err
}
desired := s.scaling.DesiredCount(&metrics, &asg) + int64(s.instanceBuffer)
if desired > asg.MaxSize {
log.Printf("⚠️ Desired count exceed MaxSize, capping at %d", asg.MaxSize)
desired = asg.MaxSize
}
if desired < asg.MinSize {
log.Printf("⚠️ Desired count is less than MinSize, capping at %d", asg.MinSize)
desired = asg.MinSize
}
if desired > asg.DesiredCount {
return metrics.PollDuration, s.scaleOut(desired, asg)
}
if asg.DesiredCount > desired {
return metrics.PollDuration, s.scaleIn(desired, asg)
}
log.Printf("No scaling required, currently %d", asg.DesiredCount)
return metrics.PollDuration, nil
}
func (s *Scaler) scaleIn(desired int64, current AutoscaleGroupDetails) error {
if s.scaleInParams.Disable {
return nil
}
// If we've scaled down before, check if a cooldown should be enforced
if !s.scaleInParams.LastEvent.IsZero() {
lastScaleInEvent := s.scaleInParams.LastEvent
lastScaleOutEvent := s.scaleOutParams.LastEvent
lastEvent := lastScaleInEvent
if s.scaleOnlyAfterAllEvent && lastScaleInEvent.Before(lastScaleOutEvent) {
lastEvent = lastScaleOutEvent
}
cooldownRemaining := s.scaleInParams.CooldownPeriod - time.Since(lastEvent)
if cooldownRemaining > 0 {
log.Printf("⏲ Want to scale IN but in cooldown for %d seconds", cooldownRemaining/time.Second)
return nil
}
}
// Calculate the change in the desired count, will be negative
change := desired - current.DesiredCount
// Apply scaling factor if one is given
if factor := s.scaleInParams.Factor; factor != 0 {
// Use Floor to avoid never reaching upper bound
factoredChange := int64(math.Floor(float64(change) * factor))
switch {
case factoredChange < change:
log.Printf("👮️ Increasing scale-in of %d by factor of %0.2f",
change, factor)
case factoredChange > change:
log.Printf("👮️ Decreasing scale-in of %d by factor of %0.2f",
change, factor)
default:
log.Printf("👮️ Scale-in factor of %0.2f was ignored",
factor)
}
desired = current.DesiredCount + factoredChange
if desired < current.MinSize {
log.Printf("⚠️ Post scalein-factor desired count lower than MinSize, capping at %d", current.MinSize)
desired = current.MinSize
}
}
// Correct negative values if we get them
if desired < 0 {
desired = 0
}
log.Printf("Scaling IN 📉 to %d instances (currently %d)", desired, current.DesiredCount)
if err := s.setDesiredCapacity(desired); err != nil {
return err
}
s.scaleInParams.LastEvent = time.Now()
return nil
}
func (s *Scaler) scaleOut(desired int64, current AutoscaleGroupDetails) error {
if s.scaleOutParams.Disable {
return nil
}
// If we've scaled out before, check if a cooldown should be enforced
if !s.scaleOutParams.LastEvent.IsZero() {
lastScaleInEvent := s.scaleInParams.LastEvent
lastScaleOutEvent := s.scaleOutParams.LastEvent
lastEvent := lastScaleOutEvent
if s.scaleOnlyAfterAllEvent && lastScaleOutEvent.Before(lastScaleInEvent) {
lastEvent = lastScaleInEvent
}
cooldownRemaining := s.scaleOutParams.CooldownPeriod - time.Since(lastEvent)
if cooldownRemaining > 0 {
log.Printf("⏲ Want to scale OUT but in cooldown for %d seconds", cooldownRemaining/time.Second)
return nil
}
}
// Calculate the change in the desired count, will be positive
change := desired - current.DesiredCount
// Apply scaling factor if one is given
if s.scaleOutParams.Factor != 0 {
// Use Ceil to avoid never reaching upper bound
factoredChange := int64(math.Ceil(float64(change) * s.scaleOutParams.Factor))
switch {
case factoredChange > change:
log.Printf("👮️ Increasing scale-out of %d by factor of %0.2f",
change, s.scaleOutParams.Factor)
case factoredChange < change:
log.Printf("👮️ Decreasing scale-out of %d by factor of %0.2f",
change, s.scaleOutParams.Factor)
default:
log.Printf("👮️ Scale-out factor of %0.2f was ignored",
s.scaleOutParams.Factor)
}
desired = current.DesiredCount + factoredChange
if desired > current.MaxSize {
log.Printf("⚠️ Post scaleout-factor desired count exceed MaxSize, capping at %d", current.MaxSize)
desired = current.MaxSize
}
}
log.Printf("Scaling OUT 📈 to %d instances (currently %d)", desired, current.DesiredCount)
if err := s.setDesiredCapacity(desired); err != nil {
return err
}
s.scaleOutParams.LastEvent = time.Now()
return nil
}
func (s *Scaler) setDesiredCapacity(desired int64) error {
t := time.Now()
if err := s.autoscaling.SetDesiredCapacity(desired); err != nil {
return err
}
log.Printf("↳ Set desired to %d (took %v)", desired, time.Now().Sub(t))
return nil
}
func (s *Scaler) LastScaleOut() time.Time {
return s.scaleOutParams.LastEvent
}
func (s *Scaler) LastScaleIn() time.Time {
return s.scaleInParams.LastEvent
}
type buildkiteDriver struct {
client *buildkite.Client
queue string
}
func (a *buildkiteDriver) GetAgentMetrics() (buildkite.AgentMetrics, error) {
return a.client.GetAgentMetrics(a.queue)
}