-
Notifications
You must be signed in to change notification settings - Fork 600
/
autoscaler.go
283 lines (242 loc) · 8.68 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
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
/*
Copyright 2020 The Knative Authors
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 statefulset
import (
"context"
"math"
"sync"
"time"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
clientappsv1 "k8s.io/client-go/kubernetes/typed/apps/v1"
"knative.dev/eventing/pkg/scheduler"
st "knative.dev/eventing/pkg/scheduler/state"
kubeclient "knative.dev/pkg/client/injection/kube/client"
"knative.dev/pkg/logging"
)
type Autoscaler interface {
// Start runs the autoscaler until cancelled.
Start(ctx context.Context)
// Autoscale is used to immediately trigger the autoscaler with the hint
// that pending number of vreplicas couldn't be scheduled.
Autoscale(ctx context.Context, attemptScaleDown bool, pending int32)
}
type autoscaler struct {
statefulSetClient clientappsv1.StatefulSetInterface
statefulSetName string
vpodLister scheduler.VPodLister
logger *zap.SugaredLogger
stateAccessor st.StateAccessor
trigger chan int32
evictor scheduler.Evictor
// capacity is the total number of virtual replicas available per pod.
capacity int32
// refreshPeriod is how often the autoscaler tries to scale down the statefulset
refreshPeriod time.Duration
lock sync.Locker
}
func NewAutoscaler(ctx context.Context,
namespace, name string,
lister scheduler.VPodLister,
stateAccessor st.StateAccessor,
evictor scheduler.Evictor,
refreshPeriod time.Duration,
capacity int32) Autoscaler {
return &autoscaler{
logger: logging.FromContext(ctx),
statefulSetClient: kubeclient.Get(ctx).AppsV1().StatefulSets(namespace),
statefulSetName: name,
vpodLister: lister,
stateAccessor: stateAccessor,
evictor: evictor,
trigger: make(chan int32, 1),
capacity: capacity,
refreshPeriod: refreshPeriod,
lock: new(sync.Mutex),
}
}
func (a *autoscaler) Start(ctx context.Context) {
attemptScaleDown := false
pending := int32(0)
for {
select {
case <-ctx.Done():
return
case <-time.After(a.refreshPeriod):
attemptScaleDown = true
case pending = <-a.trigger:
attemptScaleDown = false
}
// Retry a few times, just so that we don't have to wait for the next beat when
// a transient error occurs
a.syncAutoscale(ctx, attemptScaleDown, pending)
pending = int32(0)
}
}
func (a *autoscaler) Autoscale(ctx context.Context, attemptScaleDown bool, pending int32) {
a.syncAutoscale(ctx, attemptScaleDown, pending)
}
func (a *autoscaler) syncAutoscale(ctx context.Context, attemptScaleDown bool, pending int32) {
a.lock.Lock()
defer a.lock.Unlock()
wait.Poll(500*time.Millisecond, 5*time.Second, func() (bool, error) {
err := a.doautoscale(ctx, attemptScaleDown, pending)
return err == nil, nil
})
}
func (a *autoscaler) doautoscale(ctx context.Context, attemptScaleDown bool, pending int32) error {
state, err := a.stateAccessor.State(nil)
if err != nil {
a.logger.Info("error while refreshing scheduler state (will retry)", zap.Error(err))
return err
}
scale, err := a.statefulSetClient.GetScale(ctx, a.statefulSetName, metav1.GetOptions{})
if err != nil {
// skip a beat
a.logger.Infow("failed to get scale subresource", zap.Error(err))
return err
}
a.logger.Infow("checking adapter capacity",
zap.Int32("pending", pending),
zap.Int32("replicas", scale.Spec.Replicas),
zap.Int32("last ordinal", state.LastOrdinal))
var scaleUpFactor, newreplicas, minNumPods int32
scaleUpFactor = 1 // Non-HA scaling
if state.SchedPolicy != nil && contains(nil, state.SchedPolicy.Priorities, st.AvailabilityZonePriority) { //HA scaling across zones
scaleUpFactor = state.NumZones
}
if state.SchedPolicy != nil && contains(nil, state.SchedPolicy.Priorities, st.AvailabilityNodePriority) { //HA scaling across nodes
scaleUpFactor = state.NumNodes
}
newreplicas = state.LastOrdinal + 1 // Ideal number
// Take into account pending replicas and pods that are already filled (for even pod spread)
if pending > 0 {
// Make sure to allocate enough pods for holding all pending replicas.
if state.SchedPolicy != nil && contains(state.SchedPolicy.Predicates, nil, st.EvenPodSpread) && len(state.FreeCap) > 0 { //HA scaling across pods
leastNonZeroCapacity := a.minNonZeroInt(state.FreeCap)
minNumPods = int32(math.Ceil(float64(pending) / float64(leastNonZeroCapacity)))
} else {
minNumPods = int32(math.Ceil(float64(pending) / float64(a.capacity)))
}
newreplicas += int32(math.Ceil(float64(minNumPods)/float64(scaleUpFactor)) * float64(scaleUpFactor))
}
// Make sure to never scale down past the last ordinal
if newreplicas <= state.LastOrdinal {
newreplicas = state.LastOrdinal + scaleUpFactor
}
// Only scale down if permitted
if !attemptScaleDown && newreplicas < scale.Spec.Replicas {
newreplicas = scale.Spec.Replicas
}
if newreplicas != scale.Spec.Replicas {
scale.Spec.Replicas = newreplicas
a.logger.Infow("updating adapter replicas", zap.Int32("replicas", scale.Spec.Replicas))
_, err = a.statefulSetClient.UpdateScale(ctx, a.statefulSetName, scale, metav1.UpdateOptions{})
if err != nil {
a.logger.Errorw("updating scale subresource failed", zap.Error(err))
return err
}
} else if attemptScaleDown {
// since the number of replicas hasn't changed and time has approached to scale down,
// take the opportunity to compact the vreplicas
a.mayCompact(state, scaleUpFactor)
}
return nil
}
func (a *autoscaler) mayCompact(s *st.State, scaleUpFactor int32) {
// when there is only one pod there is nothing to move or number of pods is just enough!
if s.LastOrdinal < 1 || len(s.SchedulablePods) <= int(scaleUpFactor) {
return
}
if s.SchedulerPolicy == scheduler.MAXFILLUP {
// Determine if there is enough free capacity to
// move all vreplicas placed in the last pod to pods with a lower ordinal
freeCapacity := s.FreeCapacity() - s.Free(s.LastOrdinal)
usedInLastPod := s.Capacity - s.Free(s.LastOrdinal)
if freeCapacity >= usedInLastPod {
err := a.compact(s, scaleUpFactor)
if err != nil {
a.logger.Errorw("vreplicas compaction failed", zap.Error(err))
}
}
// only do 1 replica at a time to avoid overloading the scheduler with too many
// rescheduling requests.
} else if s.SchedPolicy != nil {
//Below calculation can be optimized to work for recovery scenarios when nodes/zones are lost due to failure
freeCapacity := s.FreeCapacity()
usedInLastXPods := s.Capacity * scaleUpFactor
for i := int32(0); i < scaleUpFactor && s.LastOrdinal-i >= 0; i++ {
freeCapacity = freeCapacity - s.Free(s.LastOrdinal-i)
usedInLastXPods = usedInLastXPods - s.Free(s.LastOrdinal-i)
}
if (freeCapacity >= usedInLastXPods) && //remaining pods can hold all vreps from evicted pods
(s.Replicas-scaleUpFactor >= scaleUpFactor) { //remaining # of pods is enough for HA scaling
err := a.compact(s, scaleUpFactor)
if err != nil {
a.logger.Errorw("vreplicas compaction failed", zap.Error(err))
}
}
}
}
func (a *autoscaler) compact(s *st.State, scaleUpFactor int32) error {
var pod *v1.Pod
vpods, err := a.vpodLister()
if err != nil {
return err
}
for _, vpod := range vpods {
placements := vpod.GetPlacements()
for i := len(placements) - 1; i >= 0; i-- { //start from the last placement
for j := int32(0); j < scaleUpFactor; j++ {
ordinal := st.OrdinalFromPodName(placements[i].PodName)
if ordinal == s.LastOrdinal-j {
wait.PollImmediate(50*time.Millisecond, 5*time.Second, func() (bool, error) {
if s.PodLister != nil {
pod, err = s.PodLister.Get(placements[i].PodName)
}
return err == nil, nil
})
err = a.evictor(pod, vpod, &placements[i])
if err != nil {
return err
}
}
}
}
}
return nil
}
func contains(preds []scheduler.PredicatePolicy, priors []scheduler.PriorityPolicy, name string) bool {
for _, v := range preds {
if v.Name == name {
return true
}
}
for _, v := range priors {
if v.Name == name {
return true
}
}
return false
}
func (a *autoscaler) minNonZeroInt(slice []int32) int32 {
min := a.capacity
for _, v := range slice {
if v < min && v > 0 {
min = v
}
}
return min
}