forked from kubernetes-retired/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_autoscaler.go
287 lines (246 loc) · 9.96 KB
/
static_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
284
285
286
287
/*
Copyright 2016 The Kubernetes 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 core
import (
"time"
"k8s.io/contrib/cluster-autoscaler/clusterstate/utils"
"k8s.io/contrib/cluster-autoscaler/metrics"
kube_util "k8s.io/contrib/cluster-autoscaler/utils/kubernetes"
kube_record "k8s.io/client-go/tools/record"
kube_client "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
"github.com/golang/glog"
"k8s.io/contrib/cluster-autoscaler/simulator"
)
// StaticAutoscaler is an autoscaler which has all the core functionality of a CA but without the reconfiguration feature
type StaticAutoscaler struct {
// AutoscalingContext consists of validated settings and options for this autoscaler
*AutoscalingContext
kube_util.ListerRegistry
lastScaleUpTime time.Time
lastScaleDownFailedTrial time.Time
scaleDown *ScaleDown
}
// NewStaticAutoscaler creates an instance of Autoscaler filled with provided parameters
func NewStaticAutoscaler(opts AutoscalingOptions, predicateChecker *simulator.PredicateChecker,
kubeClient kube_client.Interface, kubeEventRecorder kube_record.EventRecorder, listerRegistry kube_util.ListerRegistry) *StaticAutoscaler {
logRecorder, err := utils.NewStatusMapRecorder(kubeClient, kubeEventRecorder, opts.WriteStatusConfigMap)
if err != nil {
glog.Error("Failed to initialize status configmap, unable to write status events")
// Get a dummy, so we can at least safely call the methods
// TODO(maciekpytel): recover from this after successfull status configmap update?
logRecorder, _ = utils.NewStatusMapRecorder(kubeClient, kubeEventRecorder, false)
}
autoscalingContext := NewAutoscalingContext(opts, predicateChecker, kubeClient, kubeEventRecorder, logRecorder)
scaleDown := NewScaleDown(autoscalingContext)
return &StaticAutoscaler{
AutoscalingContext: autoscalingContext,
ListerRegistry: listerRegistry,
lastScaleUpTime: time.Now(),
lastScaleDownFailedTrial: time.Now(),
scaleDown: scaleDown,
}
}
// CleanUp cleans up ToBeDeleted taints added by the previously run and then failed CA
func (a *StaticAutoscaler) CleanUp() {
// CA can die at any time. Removing taints that might have been left from the previous run.
if readyNodes, err := a.ReadyNodeLister().List(); err != nil {
cleanToBeDeleted(readyNodes, a.AutoscalingContext.ClientSet, a.Recorder)
}
}
// RunOnce iterates over node groups and scales them up/down if necessary
func (a *StaticAutoscaler) RunOnce(currentTime time.Time) {
readyNodeLister := a.ReadyNodeLister()
allNodeLister := a.AllNodeLister()
unschedulablePodLister := a.UnschedulablePodLister()
scheduledPodLister := a.ScheduledPodLister()
pdbLister := a.PodDisruptionBudgetLister()
scaleDown := a.scaleDown
autoscalingContext := a.AutoscalingContext
readyNodes, err := readyNodeLister.List()
if err != nil {
glog.Errorf("Failed to list ready nodes: %v", err)
return
}
if len(readyNodes) == 0 {
glog.Errorf("No ready nodes in the cluster")
scaleDown.CleanUpUnneededNodes()
return
}
allNodes, err := allNodeLister.List()
if err != nil {
glog.Errorf("Failed to list all nodes: %v", err)
return
}
if len(allNodes) == 0 {
glog.Errorf("No nodes in the cluster")
scaleDown.CleanUpUnneededNodes()
return
}
a.ClusterStateRegistry.UpdateNodes(allNodes, currentTime)
// Update status information when the loop is done (regardless of reason)
defer func() {
if autoscalingContext.WriteStatusConfigMap {
status := a.ClusterStateRegistry.GetStatus(time.Now())
utils.WriteStatusConfigMap(autoscalingContext.ClientSet, status.GetReadableString(), a.AutoscalingContext.LogRecorder)
}
}()
if !a.ClusterStateRegistry.IsClusterHealthy() {
glog.Warningf("Cluster is not ready for autoscaling: %v", err)
scaleDown.CleanUpUnneededNodes()
return
}
// Check if there are any nodes that failed to register in kuberentes
// master.
unregisteredNodes := a.ClusterStateRegistry.GetUnregisteredNodes()
if len(unregisteredNodes) > 0 {
glog.V(1).Infof("%d unregistered nodes present", len(unregisteredNodes))
removedAny, err := removeOldUnregisteredNodes(unregisteredNodes, autoscalingContext, time.Now())
// There was a problem with removing unregistered nodes. Retry in the next loop.
if err != nil {
if removedAny {
glog.Warningf("Some unregistered nodes were removed, but got error: %v", err)
} else {
glog.Warningf("Failed to remove unregistered nodes: %v", err)
}
return
}
// Some nodes were removed. Let's skip this iteration, the next one should be better.
if removedAny {
glog.V(0).Infof("Some unregistered nodes were removed, skipping iteration")
return
}
}
// Check if there has been a constant difference between the number of nodes in k8s and
// the number of nodes on the cloud provider side.
// TODO: andrewskim - add protection for ready AWS nodes.
fixedSomething, err := fixNodeGroupSize(autoscalingContext, time.Now())
if err != nil {
glog.Warningf("Failed to fix node group sizes: %v", err)
return
}
if fixedSomething {
glog.V(0).Infof("Some node group target size was fixed, skipping the iteration")
return
}
allUnschedulablePods, err := unschedulablePodLister.List()
if err != nil {
glog.Errorf("Failed to list unscheduled pods: %v", err)
return
}
allScheduled, err := scheduledPodLister.List()
if err != nil {
glog.Errorf("Failed to list scheduled pods: %v", err)
return
}
// We need to reset all pods that have been marked as unschedulable not after
// the newest node became available for the scheduler.
allNodesAvailableTime := GetAllNodesAvailableTime(readyNodes)
podsToReset, unschedulablePodsToHelp := SlicePodsByPodScheduledTime(allUnschedulablePods, allNodesAvailableTime)
ResetPodScheduledCondition(a.AutoscalingContext.ClientSet, podsToReset)
// We need to check whether pods marked as unschedulable are actually unschedulable.
// This should prevent from adding unnecessary nodes. Example of such situation:
// - CA and Scheduler has slightly different configuration
// - Scheduler can't schedule a pod and marks it as unschedulable
// - CA added a node which should help the pod
// - Scheduler doesn't schedule the pod on the new node
// because according to it logic it doesn't fit there
// - CA see the pod is still unschedulable, so it adds another node to help it
//
// With the check enabled the last point won't happen because CA will ignore a pod
// which is supposed to schedule on an existing node.
//
// Without below check cluster might be unnecessary scaled up to the max allowed size
// in the describe situation.
schedulablePodsPresent := false
if a.VerifyUnschedulablePods {
glog.V(4).Infof("Filtering out schedulables")
newUnschedulablePodsToHelp := FilterOutSchedulable(unschedulablePodsToHelp, readyNodes, allScheduled,
a.PredicateChecker)
if len(newUnschedulablePodsToHelp) != len(unschedulablePodsToHelp) {
glog.V(2).Info("Schedulable pods present")
schedulablePodsPresent = true
} else {
glog.V(4).Info("No schedulable pods")
}
unschedulablePodsToHelp = newUnschedulablePodsToHelp
}
if len(unschedulablePodsToHelp) == 0 {
glog.V(1).Info("No unschedulable pods")
} else if a.MaxNodesTotal > 0 && len(readyNodes) >= a.MaxNodesTotal {
glog.V(1).Info("Max total nodes in cluster reached")
} else {
scaleUpStart := time.Now()
metrics.UpdateLastTime("scaleup")
scaledUp, err := ScaleUp(autoscalingContext, unschedulablePodsToHelp, readyNodes)
metrics.UpdateDuration("scaleup", scaleUpStart)
if err != nil {
glog.Errorf("Failed to scale up: %v", err)
return
} else if scaledUp {
a.lastScaleUpTime = time.Now()
// No scale down in this iteration.
return
}
}
if a.ScaleDownEnabled {
unneededStart := time.Now()
pdbs, err := pdbLister.List()
if err != nil {
glog.Errorf("Failed to list pod disruption budgets: %v", err)
return
}
// In dry run only utilization is updated
calculateUnneededOnly := a.lastScaleUpTime.Add(a.ScaleDownDelay).After(time.Now()) ||
a.lastScaleDownFailedTrial.Add(a.ScaleDownTrialInterval).After(time.Now()) ||
schedulablePodsPresent
glog.V(4).Infof("Scale down status: unneededOnly=%v lastScaleUpTime=%s "+
"lastScaleDownFailedTrail=%s schedulablePodsPresent=%v", calculateUnneededOnly,
a.lastScaleUpTime, a.lastScaleDownFailedTrial, schedulablePodsPresent)
metrics.UpdateLastTime("findUnneeded")
glog.V(4).Infof("Calculating unneeded nodes")
scaleDown.CleanUp(time.Now())
err = scaleDown.UpdateUnneededNodes(allNodes, allScheduled, time.Now(), pdbs)
if err != nil {
glog.Warningf("Failed to scale down: %v", err)
return
}
metrics.UpdateDuration("findUnneeded", unneededStart)
for key, val := range scaleDown.unneededNodes {
if glog.V(4) {
glog.V(4).Infof("%s is unneeded since %s duration %s", key, val.String(), time.Now().Sub(val).String())
}
}
if !calculateUnneededOnly {
glog.V(4).Infof("Starting scale down")
scaleDownStart := time.Now()
metrics.UpdateLastTime("scaledown")
result, err := scaleDown.TryToScaleDown(allNodes, allScheduled, pdbs)
metrics.UpdateDuration("scaledown", scaleDownStart)
// TODO: revisit result handling
if err != nil {
glog.Errorf("Failed to scale down: %v", err)
} else {
if result == ScaleDownError || result == ScaleDownNoNodeDeleted {
a.lastScaleDownFailedTrial = time.Now()
}
}
}
}
}
// ExitCleanUp removes status configmap.
func (a *StaticAutoscaler) ExitCleanUp() {
if !a.AutoscalingContext.WriteStatusConfigMap {
return
}
utils.DeleteStatusConfigMap(a.AutoscalingContext.ClientSet)
}