forked from openshift/cluster-api-actuator-pkg
/
autoscaler.go
343 lines (310 loc) · 12.1 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package autoscaler
import (
"context"
"fmt"
"path"
"strings"
"time"
"github.com/golang/glog"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
e2e "github.com/openshift/cluster-api-actuator-pkg/pkg/e2e/framework"
mapiv1beta1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1"
caov1 "github.com/openshift/cluster-autoscaler-operator/pkg/apis/autoscaling/v1"
caov1beta1 "github.com/openshift/cluster-autoscaler-operator/pkg/apis/autoscaling/v1beta1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/pointer"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
autoscalingTestLabel = "test.autoscaling.label"
clusterAutoscalerComponent = "cluster-autoscaler"
clusterAutoscalerObjectKind = "ConfigMap"
clusterAutoscalerScaledUpGroup = "ScaledUpGroup"
clusterAutoscalerScaleDownEmpty = "ScaleDownEmpty"
clusterAutoscalerMaxNodesTotalReached = "MaxNodesTotalReached"
pollingInterval = 3 * time.Second
)
func newWorkLoad() *batchv1.Job {
return &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: "workload",
Namespace: "default",
Labels: map[string]string{autoscalingTestLabel: ""},
},
TypeMeta: metav1.TypeMeta{
Kind: "Job",
APIVersion: "batch/v1",
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "workload",
Image: "busybox",
Command: []string{
"sleep",
"86400", // 1 day
},
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
"memory": resource.MustParse("500Mi"),
"cpu": resource.MustParse("500m"),
},
},
},
},
RestartPolicy: corev1.RestartPolicy("Never"),
NodeSelector: map[string]string{
e2e.WorkerNodeRoleLabel: "",
},
Tolerations: []corev1.Toleration{
{
Key: "kubemark",
Operator: corev1.TolerationOpExists,
},
},
},
},
BackoffLimit: pointer.Int32Ptr(4),
Completions: pointer.Int32Ptr(50),
Parallelism: pointer.Int32Ptr(50),
},
}
}
// Build default CA resource to allow fast scaling up and down
func clusterAutoscalerResource(maxNodesTotal int) *caov1.ClusterAutoscaler {
tenSecondString := "10s"
// Choose a time that is at least twice as the sync period
// and that has high least common multiple to avoid a case
// when a node is considered to be empty even if there are
// pods already scheduled and running on the node.
unneededTimeString := "23s"
return &caov1.ClusterAutoscaler{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
Namespace: e2e.TestContext.MachineApiNamespace,
Labels: map[string]string{
autoscalingTestLabel: "",
},
},
TypeMeta: metav1.TypeMeta{
Kind: "ClusterAutoscaler",
APIVersion: "autoscaling.openshift.io/v1",
},
Spec: caov1.ClusterAutoscalerSpec{
ScaleDown: &caov1.ScaleDownConfig{
Enabled: true,
DelayAfterAdd: &tenSecondString,
DelayAfterDelete: &tenSecondString,
DelayAfterFailure: &tenSecondString,
UnneededTime: &unneededTimeString,
},
ResourceLimits: &caov1.ResourceLimits{
MaxNodesTotal: pointer.Int32Ptr(int32(maxNodesTotal)),
},
},
}
}
// Build MA resource from targeted machineset
func machineAutoscalerResource(targetMachineSet *mapiv1beta1.MachineSet, minReplicas, maxReplicas int32) *caov1beta1.MachineAutoscaler {
return &caov1beta1.MachineAutoscaler{
ObjectMeta: metav1.ObjectMeta{
GenerateName: fmt.Sprintf("autoscale-%s", targetMachineSet.Name),
Namespace: e2e.TestContext.MachineApiNamespace,
Labels: map[string]string{
autoscalingTestLabel: "",
},
},
TypeMeta: metav1.TypeMeta{
Kind: "MachineAutoscaler",
APIVersion: "autoscaling.openshift.io/v1beta1",
},
Spec: caov1beta1.MachineAutoscalerSpec{
MaxReplicas: maxReplicas,
MinReplicas: minReplicas,
ScaleTargetRef: caov1beta1.CrossVersionObjectReference{
Name: targetMachineSet.Name,
Kind: "MachineSet",
APIVersion: "machine.openshift.io/v1beta1",
},
},
}
}
func newScaleUpCounter(w *eventWatcher, v uint32, scaledGroups map[string]bool) *eventCounter {
isAutoscalerScaleUpEvent := func(event *corev1.Event) bool {
return event.Source.Component == clusterAutoscalerComponent &&
event.Reason == clusterAutoscalerScaledUpGroup &&
event.InvolvedObject.Kind == clusterAutoscalerObjectKind &&
strings.HasPrefix(event.Message, "Scale-up: setting group")
}
matchGroup := func(event *corev1.Event) bool {
if !isAutoscalerScaleUpEvent(event) {
return false
}
for k := range scaledGroups {
if !scaledGroups[k] && strings.HasPrefix(event.Message, fmt.Sprintf("Scale-up: group %s size set to", k)) {
scaledGroups[k] = true
}
}
return true
}
c := newEventCounter(w, matchGroup, v, increment)
c.enable()
return c
}
func newScaleDownCounter(w *eventWatcher, v uint32) *eventCounter {
isAutoscalerScaleDownEvent := func(event *corev1.Event) bool {
return event.Source.Component == clusterAutoscalerComponent &&
event.Reason == clusterAutoscalerScaleDownEmpty &&
event.InvolvedObject.Kind == clusterAutoscalerObjectKind &&
strings.HasPrefix(event.Message, "Scale-down: empty node")
}
c := newEventCounter(w, isAutoscalerScaleDownEvent, v, decrement)
c.enable()
return c
}
func newMaxNodesTotalReachedCounter(w *eventWatcher, v uint32) *eventCounter {
isAutoscalerMaxNodesTotalEvent := func(event *corev1.Event) bool {
return event.Source.Component == clusterAutoscalerComponent &&
event.Reason == clusterAutoscalerMaxNodesTotalReached &&
event.InvolvedObject.Kind == clusterAutoscalerObjectKind &&
strings.HasPrefix(event.Message, "Max total nodes in cluster reached")
}
c := newEventCounter(w, isAutoscalerMaxNodesTotalEvent, v, increment)
c.enable()
return c
}
func remaining(t time.Time) time.Duration {
return t.Sub(time.Now()).Round(time.Second)
}
var _ = g.Describe("[Feature:Machines][Serial] Autoscaler should", func() {
g.It("scale up and down", func() {
defer g.GinkgoRecover()
clientset, err := e2e.LoadClientset()
o.Expect(err).NotTo(o.HaveOccurred())
var client runtimeclient.Client
client, err = e2e.LoadClient()
o.Expect(err).NotTo(o.HaveOccurred())
// Anything we create we must cleanup
var cleanupObjects []runtime.Object
defer func() {
cascadeDelete := metav1.DeletePropagationForeground
for _, obj := range cleanupObjects {
if err = client.Delete(context.TODO(), obj, func(opt *runtimeclient.DeleteOptions) {
opt.PropagationPolicy = &cascadeDelete
}); err != nil {
glog.Errorf("error deleting object: %v", err)
}
}
}()
g.By("Getting machinesets")
machineSets, err := e2e.GetMachineSets(context.TODO(), client)
o.Expect(err).NotTo(o.HaveOccurred())
o.Expect(len(machineSets)).To(o.BeNumerically(">=", 2))
g.By("Getting nodes")
nodes, err := e2e.GetNodes(client)
o.Expect(err).NotTo(o.HaveOccurred())
o.Expect(len(nodes)).To(o.BeNumerically(">=", 1))
g.By(fmt.Sprintf("Creating %v machineautoscalers", len(machineSets)))
var clusterExpansionSize int
for i := range machineSets {
min := pointer.Int32PtrDerefOr(machineSets[i].Spec.Replicas, 1)
// We only want each machineautoscaler
// resource to be able to grow by one
// additional node.
max := min + 1
clusterExpansionSize += 1
glog.Infof("Create MachineAutoscaler backed by MachineSet %s/%s - min:%v, max:%v", machineSets[i].Namespace, machineSets[i].Name, min, max)
asr := machineAutoscalerResource(&machineSets[i], min, max)
o.Expect(client.Create(context.TODO(), asr)).Should(o.Succeed())
cleanupObjects = append(cleanupObjects, runtime.Object(asr))
}
o.Expect(clusterExpansionSize).To(o.BeNumerically(">", 1))
// We want to scale out to max-cluster-size-1. We
// choose max-1 because we want to test that
// maxNodesTotal is respected by the
// cluster-autoscaler. If maxNodesTotal ==
// max-cluster-size then no MaxNodesTotalReached
// event will be generated.
maxNodesTotal := len(nodes) + clusterExpansionSize - 1
eventWatcher := newEventWatcher(clientset)
o.Expect(eventWatcher.run()).Should(o.BeTrue())
defer eventWatcher.stop()
// Log cluster-autoscaler events
eventWatcher.onEvent(matchAnyEvent, func(e *corev1.Event) {
if e.Source.Component == clusterAutoscalerComponent {
glog.Infof("%s: %s", e.InvolvedObject.Name, e.Message)
}
}).enable()
g.By(fmt.Sprintf("Creating ClusterAutoscaler configured with maxNodesTotal:%v", maxNodesTotal))
clusterAutoscaler := clusterAutoscalerResource(maxNodesTotal)
o.Expect(client.Create(context.TODO(), clusterAutoscaler)).Should(o.Succeed())
cleanupObjects = append(cleanupObjects, runtime.Object(clusterAutoscaler))
g.By("Creating scale-out workload")
scaledGroups := map[string]bool{}
for i := range machineSets {
scaledGroups[path.Join(machineSets[i].Namespace, machineSets[i].Name)] = false
}
scaleUpCounter := newScaleUpCounter(eventWatcher, 0, scaledGroups)
maxNodesTotalReachedCounter := newMaxNodesTotalReachedCounter(eventWatcher, 0)
workload := newWorkLoad()
o.Expect(client.Create(context.TODO(), workload)).Should(o.Succeed())
cleanupObjects = append(cleanupObjects, runtime.Object(workload))
testDuration := time.Now().Add(time.Duration(e2e.WaitLong))
o.Eventually(func() bool {
v := scaleUpCounter.get()
glog.Infof("[%s remaining] Expecting %v %q events; observed %v",
remaining(testDuration), clusterExpansionSize-1, clusterAutoscalerScaledUpGroup, v)
return v == uint32(clusterExpansionSize-1)
}, e2e.WaitLong, pollingInterval).Should(o.BeTrue())
// The cluster-autoscaler can keep on generating
// ScaledUpGroup events but in this scenario we are
// expecting no more as we explicitly capped the
// cluster size with maxNodesTotal (i.e.,
// clusterExpansionSize -1). We run for a period of
// time asserting that the cluster does not exceed the
// capped size.
testDuration = time.Now().Add(time.Duration(e2e.WaitShort))
o.Eventually(func() uint32 {
v := maxNodesTotalReachedCounter.get()
glog.Infof("[%s remaining] Waiting for %s to generate a %q event; observed %v",
remaining(testDuration), clusterAutoscalerComponent, clusterAutoscalerMaxNodesTotalReached, v)
return v
}, e2e.WaitShort, 3*time.Second).Should(o.BeNumerically(">=", 1))
testDuration = time.Now().Add(time.Duration(e2e.WaitShort))
o.Consistently(func() bool {
v := scaleUpCounter.get()
glog.Infof("[%s remaining] At max cluster size and expecting no more %q events; currently have %v, max=%v",
remaining(testDuration), clusterAutoscalerScaledUpGroup, v, clusterExpansionSize-1)
return v == uint32(clusterExpansionSize-1)
}, e2e.WaitShort, pollingInterval).Should(o.BeTrue())
g.By("Deleting workload")
scaleDownCounter := newScaleDownCounter(eventWatcher, uint32(clusterExpansionSize-1))
o.Expect(e2e.DeleteObjectsByLabels(context.TODO(), client, map[string]string{autoscalingTestLabel: ""}, &batchv1.JobList{})).Should(o.Succeed())
if len(cleanupObjects) > 1 && cleanupObjects[len(cleanupObjects)-1] == workload {
cleanupObjects = cleanupObjects[:len(cleanupObjects)-1]
}
testDuration = time.Now().Add(time.Duration(e2e.WaitLong))
o.Eventually(func() uint32 {
v := scaleDownCounter.get()
glog.Infof("[%s remaining] Waiting for %s to generate %v more %q events",
remaining(testDuration), clusterAutoscalerComponent, v, clusterAutoscalerScaleDownEmpty)
return v
}, e2e.WaitLong, pollingInterval).Should(o.BeZero())
g.By("Waiting for scaled up nodes to be deleted")
testDuration = time.Now().Add(time.Duration(e2e.WaitMedium))
o.Eventually(func() int {
currentNodes, err := e2e.GetNodes(client)
o.Expect(err).NotTo(o.HaveOccurred())
glog.Infof("[%s remaining] Waiting fo cluster to reach original node count of %v; currently have %v",
remaining(testDuration), len(nodes), len(currentNodes))
return len(currentNodes)
}, e2e.WaitMedium, pollingInterval).Should(o.Equal(len(nodes)))
})
})