-
Notifications
You must be signed in to change notification settings - Fork 607
/
Copy pathautoscaler.go
241 lines (195 loc) · 7.6 KB
/
autoscaler.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
/*
Copyright 2021 Cortex Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package autoscaler
import (
"fmt"
"math"
"time"
"github.com/cortexlabs/cortex/pkg/config"
"github.com/cortexlabs/cortex/pkg/lib/errors"
math2 "github.com/cortexlabs/cortex/pkg/lib/math"
time2 "github.com/cortexlabs/cortex/pkg/lib/time"
"github.com/cortexlabs/cortex/pkg/operator/operator"
"github.com/cortexlabs/cortex/pkg/types/spec"
"github.com/cortexlabs/cortex/pkg/types/userconfig"
kapps "k8s.io/api/apps/v1"
)
// GetInFlightFunc is the function signature used by the autoscaler to retrieve
// the number of in-flight requests / messages
type GetInFlightFunc func(apiName string, window time.Duration) (*float64, error)
type recommendations map[time.Time]int32
func (recs recommendations) add(rec int32) {
recs[time.Now()] = rec
}
func (recs recommendations) deleteOlderThan(period time.Duration) {
for t := range recs {
if time.Since(t) > period {
delete(recs, t)
}
}
}
// Returns nil if no recommendations in the period
func (recs recommendations) maxSince(period time.Duration) *int32 {
max := int32(math.MinInt32)
foundRecommendation := false
for t, rec := range recs {
if time.Since(t) <= period && rec > max {
max = rec
foundRecommendation = true
}
}
if !foundRecommendation {
return nil
}
return &max
}
// Returns nil if no recommendations in the period
func (recs recommendations) minSince(period time.Duration) *int32 {
min := int32(math.MaxInt32)
foundRecommendation := false
for t, rec := range recs {
if time.Since(t) <= period && rec < min {
min = rec
foundRecommendation = true
}
}
if !foundRecommendation {
return nil
}
return &min
}
// AutoscaleFn returns the autoscaler function
func AutoscaleFn(initialDeployment *kapps.Deployment, apiSpec *spec.API, getInFlightFn GetInFlightFunc) (func() error, error) {
if initialDeployment == nil {
if apiSpec != nil {
return nil, errors.ErrorUnexpected("unable to find api deployment", apiSpec.Name)
}
return nil, errors.ErrorUnexpected("unable to find api deployment")
}
if apiSpec == nil {
apiName := initialDeployment.Labels["apiName"]
return nil, errors.ErrorUnexpected("unable to find api spec", apiName)
}
autoscalingSpec, err := userconfig.AutoscalingFromAnnotations(initialDeployment)
if err != nil {
return nil, err
}
apiName := apiSpec.Name
currentReplicas := *initialDeployment.Spec.Replicas
apiLogger, err := operator.GetRealtimeAPILoggerFromSpec(apiSpec)
if err != nil {
return nil, err
}
apiLogger.Infof("%s autoscaler init", apiName)
var startTime time.Time
recs := make(recommendations)
return func() error {
if startTime.IsZero() {
startTime = time.Now()
}
avgInFlight, err := getInFlightFn(apiName, autoscalingSpec.Window)
if err != nil {
return err
}
if avgInFlight == nil {
apiLogger.Debugf("%s autoscaler tick: metrics not available yet", apiName)
return nil
}
rawRecommendation := *avgInFlight / *autoscalingSpec.TargetInFlight
recommendation := int32(math.Ceil(rawRecommendation))
if rawRecommendation < float64(currentReplicas) && rawRecommendation > float64(currentReplicas)*(1-autoscalingSpec.DownscaleTolerance) {
recommendation = currentReplicas
}
if rawRecommendation > float64(currentReplicas) && rawRecommendation < float64(currentReplicas)*(1+autoscalingSpec.UpscaleTolerance) {
recommendation = currentReplicas
}
// always allow subtraction of 1
downscaleFactorFloor := math2.MinInt32(currentReplicas-1, int32(math.Ceil(float64(currentReplicas)*autoscalingSpec.MaxDownscaleFactor)))
if recommendation < downscaleFactorFloor {
recommendation = downscaleFactorFloor
}
// always allow addition of 1
upscaleFactorCeil := math2.MaxInt32(currentReplicas+1, int32(math.Ceil(float64(currentReplicas)*autoscalingSpec.MaxUpscaleFactor)))
if recommendation > upscaleFactorCeil {
recommendation = upscaleFactorCeil
}
if recommendation < autoscalingSpec.MinReplicas {
recommendation = autoscalingSpec.MinReplicas
}
if recommendation > autoscalingSpec.MaxReplicas {
recommendation = autoscalingSpec.MaxReplicas
}
// Rule of thumb: any modifications that don't consider historical recommendations should be performed before
// recording the recommendation, any modifications that use historical recommendations should be performed after
recs.add(recommendation)
// This is just for garbage collection
recs.deleteOlderThan(time2.MaxDuration(autoscalingSpec.DownscaleStabilizationPeriod, autoscalingSpec.UpscaleStabilizationPeriod))
request := recommendation
var downscaleStabilizationFloor *int32
var upscaleStabilizationCeil *int32
if request < currentReplicas {
downscaleStabilizationFloor = recs.maxSince(autoscalingSpec.DownscaleStabilizationPeriod)
if time.Since(startTime) < autoscalingSpec.DownscaleStabilizationPeriod {
request = currentReplicas
} else if downscaleStabilizationFloor != nil && request < *downscaleStabilizationFloor {
request = *downscaleStabilizationFloor
}
}
if request > currentReplicas {
upscaleStabilizationCeil = recs.minSince(autoscalingSpec.UpscaleStabilizationPeriod)
if time.Since(startTime) < autoscalingSpec.UpscaleStabilizationPeriod {
request = currentReplicas
} else if upscaleStabilizationCeil != nil && request > *upscaleStabilizationCeil {
request = *upscaleStabilizationCeil
}
}
apiLogger.Debugw(fmt.Sprintf("%s autoscaler tick", apiName),
"autoscaling", map[string]interface{}{
"avg_in_flight": *avgInFlight,
"target_in_flight": *autoscalingSpec.TargetInFlight,
"raw_recommendation": rawRecommendation,
"current_replicas": currentReplicas,
"downscale_tolerance": autoscalingSpec.DownscaleTolerance,
"upscale_tolerance": autoscalingSpec.UpscaleTolerance,
"max_downscale_factor": autoscalingSpec.MaxDownscaleFactor,
"downscale_factor_floor": downscaleFactorFloor,
"max_upscale_factor": autoscalingSpec.MaxUpscaleFactor,
"upscale_factor_ceil": upscaleFactorCeil,
"min_replicas": autoscalingSpec.MinReplicas,
"max_replicas": autoscalingSpec.MaxReplicas,
"recommendation": recommendation,
"downscale_stabilization_period": autoscalingSpec.DownscaleStabilizationPeriod.Seconds(),
"downscale_stabilization_floor": downscaleStabilizationFloor,
"upscale_stabilization_period": autoscalingSpec.UpscaleStabilizationPeriod.Seconds(),
"upscale_stabilization_ceil": upscaleStabilizationCeil,
"request": request,
},
)
if currentReplicas != request {
apiLogger.Infof("%s autoscaling event: %d -> %d", apiName, currentReplicas, request)
deployment, err := config.K8s.GetDeployment(initialDeployment.Name)
if err != nil {
return err
}
if deployment == nil {
return errors.ErrorUnexpected("unable to find k8s deployment", apiName)
}
deployment.Spec.Replicas = &request
if _, err := config.K8s.UpdateDeployment(deployment); err != nil {
return err
}
currentReplicas = request
}
return nil
}, nil
}