-
Notifications
You must be signed in to change notification settings - Fork 557
Expand file tree
/
Copy pathscheduling_benchmark_test.go
More file actions
532 lines (494 loc) · 16.9 KB
/
Copy pathscheduling_benchmark_test.go
File metadata and controls
532 lines (494 loc) · 16.9 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//go:build test_performance
/*
Copyright 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 scheduling_test
import (
"context"
"fmt"
"math"
"math/rand"
"os"
"runtime/pprof"
"testing"
"text/tabwriter"
"time"
"github.com/samber/lo"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/client-go/tools/record"
"k8s.io/utils/clock"
fakecr "sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/log"
v1 "sigs.k8s.io/karpenter/pkg/apis/v1"
"sigs.k8s.io/karpenter/pkg/cloudprovider"
"sigs.k8s.io/karpenter/pkg/cloudprovider/fake"
"sigs.k8s.io/karpenter/pkg/controllers/provisioning/scheduling"
"sigs.k8s.io/karpenter/pkg/controllers/state"
"sigs.k8s.io/karpenter/pkg/events"
"sigs.k8s.io/karpenter/pkg/operator/injection"
"sigs.k8s.io/karpenter/pkg/operator/logging"
"sigs.k8s.io/karpenter/pkg/operator/options"
"sigs.k8s.io/karpenter/pkg/test"
)
func init() {
log.SetLogger(logging.NopLogger)
}
const MinPodsPerSec = 100.0
const PrintStats = false
//nolint:gosec
var r = rand.New(rand.NewSource(42))
// To run the benchmarks use:
// `go test -tags=test_performance -run=XXX -bench=.`
//
// to get something statistically significant for comparison we need to run them several times and then
// compare the results between the old performance and the new performance.
// ```sh
//
// go test -tags=test_performance -run=XXX -bench=. -count=10 | tee /tmp/old
// # make your changes to the code
// go test -tags=test_performance -run=XXX -bench=. -count=10 | tee /tmp/new
// benchstat /tmp/old /tmp/new
//
// ```
func BenchmarkScheduling1(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(1))
}
func BenchmarkScheduling50(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(50))
}
func BenchmarkScheduling100(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(100))
}
func BenchmarkScheduling500(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(500))
}
func BenchmarkScheduling1000(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(1000))
}
func BenchmarkScheduling2000(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(2000))
}
func BenchmarkScheduling5000(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(5000))
}
func BenchmarkScheduling10000(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(10000))
}
func BenchmarkScheduling20000(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(20000))
}
func BenchmarkRespectPreferences(b *testing.B) {
benchmarkScheduler(b, makePreferencePods(4000))
}
func BenchmarkIgnorePreferences(b *testing.B) {
benchmarkScheduler(b, makePreferencePods(4000), scheduling.IgnorePreferences)
}
// BenchmarkSchedulingMultiNodePool exercises Scheduler.Solve over a fixture with
// multiple NodePools to surface regressions in cross-NodePool work such as
// buildDomainGroups (topology.go), per-NodePool instance-type fan-out, and
// per-NodePool scheduling-template construction. The single-NodePool default in
// BenchmarkScheduling* hides the cross-product cost of these paths.
func BenchmarkSchedulingMultiNodePool(b *testing.B) {
for _, nodePoolCount := range []int{5, 10, 20} {
for _, podCount := range []int{100, 500, 1000} {
b.Run(fmt.Sprintf("%dNP_%dPods", nodePoolCount, podCount), func(b *testing.B) {
benchmarkSchedulerMultiNodePool(b, makeDiversePods(podCount), nodePoolCount)
})
}
}
}
func benchmarkSchedulerMultiNodePool(b *testing.B, pods []*corev1.Pod, nodePoolCount int, opts ...scheduling.Options) {
ctx = options.ToContext(injection.WithControllerName(context.Background(), "provisioner"), test.Options())
scheduler, err := setupMultiNodePoolScheduler(ctx, pods, nodePoolCount, append(opts, scheduling.NumConcurrentReconciles(5))...)
if err != nil {
b.Fatalf("creating scheduler, %s", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
results, err := scheduler.Solve(ctx, pods)
if err != nil {
b.Fatalf("expected scheduler to schedule all pods without error, got %s", err)
}
if len(results.PodErrors) > 0 {
b.Fatalf("expected all pods to schedule, got %d pods that didn't", len(results.PodErrors))
}
}
}
func setupMultiNodePoolScheduler(ctx context.Context, pods []*corev1.Pod, nodePoolCount int, opts ...scheduling.Options) (*scheduling.Scheduler, error) {
cloudProvider = fake.NewCloudProvider()
instanceTypes := fake.InstanceTypes(100)
cloudProvider.InstanceTypes = instanceTypes
nodePools := make([]*v1.NodePool, nodePoolCount)
instanceTypesByNodePool := make(map[string][]*cloudprovider.InstanceType, nodePoolCount)
for i := range nodePools {
np := test.NodePool(v1.NodePool{
Spec: v1.NodePoolSpec{
Limits: v1.Limits{
corev1.ResourceCPU: resource.MustParse("10000000"),
corev1.ResourceMemory: resource.MustParse("10000000Gi"),
},
},
})
nodePools[i] = np
instanceTypesByNodePool[np.Name] = instanceTypes
}
client := fakecr.NewFakeClient()
clock := &clock.RealClock{}
cluster = state.NewCluster(clock, client, cloudProvider)
topology, err := scheduling.NewTopology(ctx, client, cluster, nil, nodePools, instanceTypesByNodePool, pods, opts...)
if err != nil {
return nil, fmt.Errorf("creating topology, %w", err)
}
return scheduling.NewScheduler(
ctx,
client,
nodePools,
cluster,
nil,
topology,
instanceTypesByNodePool,
nil,
events.NewRecorder(&record.FakeRecorder{}),
clock,
nil, // volumeReqsByPod
nil, // allocator
opts...,
), nil
}
// TestSchedulingProfile is used to gather profiling metrics, benchmarking is primarily done with standard
// Go benchmark functions
// go test -tags=test_performance -run=SchedulingProfile
func TestSchedulingProfile(t *testing.T) {
tw := tabwriter.NewWriter(os.Stdout, 8, 8, 2, ' ', 0)
cpuf, err := os.Create("schedule.cpuprofile")
if err != nil {
t.Fatalf("error creating CPU profile: %s", err)
}
lo.Must0(pprof.StartCPUProfile(cpuf))
defer pprof.StopCPUProfile()
heapf, err := os.Create("schedule.heapprofile")
if err != nil {
t.Fatalf("error creating heap profile: %s", err)
}
defer func() { lo.Must0(pprof.WriteHeapProfile(heapf)) }()
totalPods := 0
totalNodes := 0
var totalTime time.Duration
fmt.Fprintf(tw, "============== Generic Pods ==============\n")
for _, podCount := range []int{1, 50, 100, 500, 1000, 1500, 2000, 5000, 10000, 20000} {
start := time.Now()
res := testing.Benchmark(func(b *testing.B) {
benchmarkScheduler(b, makeDiversePods(podCount))
})
totalTime += time.Since(start) / time.Duration(res.N)
nodeCount := res.Extra["nodes"]
fmt.Fprintf(tw, "%s\t%d pods\t%d nodes\t%s per scheduling\t%s per pod\n", fmt.Sprintf("%d Pods", podCount), podCount, int(nodeCount), time.Duration(res.NsPerOp()), time.Duration(res.NsPerOp()/int64(podCount)))
totalPods += podCount
totalNodes += int(nodeCount)
}
fmt.Fprintf(tw, "============== Preference Pods ==============\n")
for _, opt := range []scheduling.Options{nil, scheduling.IgnorePreferences} {
start := time.Now()
podCount := 4000
res := testing.Benchmark(func(b *testing.B) {
benchmarkScheduler(b, makePreferencePods(podCount), opt)
})
totalTime += time.Since(start) / time.Duration(res.N)
nodeCount := res.Extra["nodes"]
fmt.Fprintf(tw, "%s\t%d pods\t%d nodes\t%s per scheduling\t%s per pod\n", lo.Ternary(opt == nil, "PreferencePolicy=Respect", "PreferencePolicy=Ignore"), podCount, int(nodeCount), time.Duration(res.NsPerOp()), time.Duration(res.NsPerOp()/int64(podCount)))
totalPods += podCount
totalNodes += int(nodeCount)
}
fmt.Fprintf(tw, "\nscheduled %d against %d nodes in total in %s %f pods/sec\n", totalPods, totalNodes, totalTime, float64(totalPods)/totalTime.Seconds())
tw.Flush()
}
func benchmarkScheduler(b *testing.B, pods []*corev1.Pod, opts ...scheduling.Options) {
ctx = options.ToContext(injection.WithControllerName(context.Background(), "provisioner"), test.Options())
scheduler, err := setupScheduler(ctx, pods, append(opts, scheduling.NumConcurrentReconciles(5))...)
if err != nil {
b.Fatalf("creating scheduler, %s", err)
}
b.ResetTimer()
// Pack benchmark
start := time.Now()
podsScheduledInRound1 := 0
nodesInRound1 := 0
for i := 0; i < b.N; i++ {
results, err := scheduler.Solve(ctx, pods)
if err != nil {
b.Fatalf("expected scheduler to schedule all pods without error, got %s", err)
}
if len(results.PodErrors) > 0 {
b.Fatalf("expected all pods to schedule, got %d pods that didn't", len(results.PodErrors))
}
if i == 0 {
minPods := math.MaxInt64
maxPods := 0
var podCounts []int
for _, n := range results.NewNodeClaims {
podCounts = append(podCounts, len(n.Pods))
podsScheduledInRound1 += len(n.Pods)
nodesInRound1 = len(results.NewNodeClaims)
if len(n.Pods) > maxPods {
maxPods = len(n.Pods)
}
if len(n.Pods) < minPods {
minPods = len(n.Pods)
}
}
if PrintStats {
meanPodsPerNode := float64(podsScheduledInRound1) / float64(nodesInRound1)
variance := 0.0
for _, pc := range podCounts {
variance += math.Pow(float64(pc)-meanPodsPerNode, 2.0)
}
variance /= float64(nodesInRound1)
stddev := math.Sqrt(variance)
fmt.Printf("400 instance types %d pods resulted in %d nodes with pods per node min=%d max=%d mean=%f stddev=%f\n",
len(pods), nodesInRound1, minPods, maxPods, meanPodsPerNode, stddev)
}
}
}
duration := time.Since(start)
podsPerSec := float64(len(pods)) / (duration.Seconds() / float64(b.N))
b.ReportMetric(podsPerSec, "pods/sec")
b.ReportMetric(float64(podsScheduledInRound1), "pods")
b.ReportMetric(float64(nodesInRound1), "nodes")
}
func setupScheduler(ctx context.Context, pods []*corev1.Pod, opts ...scheduling.Options) (*scheduling.Scheduler, error) {
nodePool := test.NodePool(v1.NodePool{
Spec: v1.NodePoolSpec{
Limits: v1.Limits{
corev1.ResourceCPU: resource.MustParse("10000000"),
corev1.ResourceMemory: resource.MustParse("10000000Gi"),
},
},
})
// Apply limits to both of the NodePools
cloudProvider = fake.NewCloudProvider()
instanceTypes := fake.InstanceTypes(400)
cloudProvider.InstanceTypes = instanceTypes
client := fakecr.NewFakeClient()
clock := &clock.RealClock{}
cluster = state.NewCluster(clock, client, cloudProvider)
topology, err := scheduling.NewTopology(ctx, client, cluster, nil, []*v1.NodePool{nodePool}, map[string][]*cloudprovider.InstanceType{
nodePool.Name: instanceTypes,
}, pods, opts...)
if err != nil {
return nil, fmt.Errorf("creating topology, %w", err)
}
return scheduling.NewScheduler(
ctx,
client,
[]*v1.NodePool{nodePool},
cluster,
nil,
topology,
map[string][]*cloudprovider.InstanceType{nodePool.Name: instanceTypes},
nil,
events.NewRecorder(&record.FakeRecorder{}),
clock,
nil, // volumeReqsByPod
nil, // allocator
opts...,
), nil
}
func makeDiversePods(count int) []*corev1.Pod {
var pods []*corev1.Pod
numTypes := 5
pods = append(pods, makeGenericPods(count/numTypes)...)
pods = append(pods, makeTopologySpreadPods(count/numTypes, corev1.LabelTopologyZone)...)
pods = append(pods, makeTopologySpreadPods(count/numTypes, corev1.LabelHostname)...)
pods = append(pods, makePodAffinityPods(count/numTypes, corev1.LabelTopologyZone)...)
pods = append(pods, makePodAntiAffinityPods(count/numTypes, corev1.LabelHostname)...)
// fill out due to count being not evenly divisible with generic pods
nRemaining := count - len(pods)
pods = append(pods, makeGenericPods(nRemaining)...)
return pods
}
func makePodAntiAffinityPods(count int, key string) []*corev1.Pod {
var pods []*corev1.Pod
// all of these pods have anti-affinity to each other
labels := map[string]string{
"app": "nginx",
}
for i := 0; i < count; i++ {
pods = append(pods, test.Pod(
test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
UID: uuid.NewUUID(), // set the UUID so the cached data is properly stored in the scheduler
},
PodAntiRequirements: []corev1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{MatchLabels: labels},
TopologyKey: key,
},
},
ResourceRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: randomCPU(),
corev1.ResourceMemory: randomMemory(),
},
}}))
}
return pods
}
func makePodAffinityPods(count int, key string) []*corev1.Pod {
var pods []*corev1.Pod
for i := 0; i < count; i++ {
// We use self-affinity here because using affinity that relies on other pod
// domains doens't guarantee that all pods can schedule. In the case where you are not
// using self-affinity and the domain doesn't exist, scheduling will fail for all pods with
// affinities against this domain
labels := randomAffinityLabels()
pods = append(pods, test.Pod(
test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
UID: uuid.NewUUID(), // set the UUID so the cached data is properly stored in the scheduler
},
PodRequirements: []corev1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{MatchLabels: labels},
TopologyKey: key,
},
},
ResourceRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: randomCPU(),
corev1.ResourceMemory: randomMemory(),
},
}}))
}
return pods
}
func makeTopologySpreadPods(count int, key string) []*corev1.Pod {
var pods []*corev1.Pod
for i := 0; i < count; i++ {
pods = append(pods, test.Pod(
test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: randomLabels(),
UID: uuid.NewUUID(), // set the UUID so the cached data is properly stored in the scheduler
},
TopologySpreadConstraints: []corev1.TopologySpreadConstraint{
{
MaxSkew: 1,
TopologyKey: key,
WhenUnsatisfiable: corev1.DoNotSchedule,
LabelSelector: &metav1.LabelSelector{
MatchLabels: randomLabels(),
},
},
},
ResourceRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: randomCPU(),
corev1.ResourceMemory: randomMemory(),
},
}}))
}
return pods
}
func makeGenericPods(count int) []*corev1.Pod {
var pods []*corev1.Pod
for i := 0; i < count; i++ {
pods = append(pods, test.Pod(
test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: randomLabels(),
UID: uuid.NewUUID(), // set the UUID so the cached data is properly stored in the scheduler
},
ResourceRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: randomCPU(),
corev1.ResourceMemory: randomMemory(),
},
}}))
}
return pods
}
func makePreferencePods(count int) []*corev1.Pod {
pods := test.Pods(count, test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "nginx",
},
},
NodePreferences: []corev1.NodeSelectorRequirement{
// This is a preference that can be satisfied
{
Key: corev1.LabelTopologyZone,
Operator: corev1.NodeSelectorOpIn,
Values: []string{"test-zone-1"},
},
},
PodAntiPreferences: []corev1.WeightedPodAffinityTerm{
// This is a preference that can't be satisfied
{
Weight: 10,
PodAffinityTerm: corev1.PodAffinityTerm{
LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{
"app": "nginx",
}},
TopologyKey: corev1.LabelTopologyZone,
},
},
// This is a preference that can be satisfied
{
Weight: 1,
PodAffinityTerm: corev1.PodAffinityTerm{
LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{
"app": "nginx",
}},
TopologyKey: corev1.LabelHostname,
},
},
},
ResourceRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: randomCPU(),
corev1.ResourceMemory: randomMemory(),
},
},
})
for _, p := range pods {
p.UID = uuid.NewUUID() // set the UUID so the cached data is properly stored in the scheduler
}
return pods
}
func randomAffinityLabels() map[string]string {
return map[string]string{
"my-affininity": randomLabelValue(),
}
}
func randomLabels() map[string]string {
return map[string]string{
"my-label": randomLabelValue(),
}
}
func randomLabelValue() string {
labelValues := []string{"a", "b", "c", "d", "e", "f", "g"}
return labelValues[r.Intn(len(labelValues))]
}
func randomMemory() resource.Quantity {
mem := []int{100, 256, 512, 1024, 2048, 4096}
return resource.MustParse(fmt.Sprintf("%dMi", mem[r.Intn(len(mem))]))
}
func randomCPU() resource.Quantity {
cpu := []int{100, 250, 500, 1000, 1500}
return resource.MustParse(fmt.Sprintf("%dm", cpu[r.Intn(len(cpu))]))
}