Skip to content

Commit 86a98d1

Browse files
committed
feat(nodeScaleDownTimeTracker): add a new metric to track unprocessed nodes during scaleDown
1 parent 524270b commit 86a98d1

File tree

5 files changed

+258
-0
lines changed

5 files changed

+258
-0
lines changed

cluster-autoscaler/config/autoscaling_options.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,11 @@ type AutoscalingOptions struct {
349349
CapacitybufferControllerEnabled bool
350350
// CapacitybufferPodInjectionEnabled tells if CA should injects fake pods for capacity buffers that are ready for provisioning
351351
CapacitybufferPodInjectionEnabled bool
352+
// LongestNodeScaleDownTimeTrackerEnabled is used to enabled/disable the tracking of longest node ScaleDown evaluation time.
353+
// We want to track all the nodes that were marked as unneeded, but were unprocessed during the ScaleDown.
354+
// If a node was unneeded, but unprocessed multiple times consecutively, we store only the earliest time it happened.
355+
// The difference between the current time and the earliest time among all unprocessed nodes will give the longest time
356+
LongestNodeScaleDownTimeTrackerEnabled bool
352357
}
353358

354359
// KubeClientOptions specify options for kube client

cluster-autoscaler/config/flags/flags.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ var (
230230
nodeDeletionCandidateTTL = flag.Duration("node-deletion-candidate-ttl", time.Duration(0), "Maximum time a node can be marked as removable before the marking becomes stale. This sets the TTL of Cluster-Autoscaler's state if the Cluste-Autoscaler deployment becomes inactive")
231231
capacitybufferControllerEnabled = flag.Bool("capacity-buffer-controller-enabled", false, "Whether to enable the default controller for capacity buffers or not")
232232
capacitybufferPodInjectionEnabled = flag.Bool("capacity-buffer-pod-injection-enabled", false, "Whether to enable pod list processor that processes ready capacity buffers and injects fake pods accordingly")
233+
longestNodeScaleDownTimeTrackerEnabled = flag.Bool("longest-node-scaledown-timetracker-enabled", false, "Whether to track the eval time of longestNodeScaleDown")
233234

234235
// Deprecated flags
235236
ignoreTaintsFlag = multiStringFlag("ignore-taint", "Specifies a taint to ignore in node templates when considering to scale a node group (Deprecated, use startup-taints instead)")
@@ -414,6 +415,7 @@ func createAutoscalingOptions() config.AutoscalingOptions {
414415
NodeDeletionCandidateTTL: *nodeDeletionCandidateTTL,
415416
CapacitybufferControllerEnabled: *capacitybufferControllerEnabled,
416417
CapacitybufferPodInjectionEnabled: *capacitybufferPodInjectionEnabled,
418+
LongestNodeScaleDownTimeTrackerEnabled: *longestNodeScaleDownTimeTrackerEnabled,
417419
}
418420
}
419421

cluster-autoscaler/core/scaledown/planner/planner.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"k8s.io/autoscaler/cluster-autoscaler/core/scaledown/resource"
3131
"k8s.io/autoscaler/cluster-autoscaler/core/scaledown/unneeded"
3232
"k8s.io/autoscaler/cluster-autoscaler/core/scaledown/unremovable"
33+
"k8s.io/autoscaler/cluster-autoscaler/metrics"
3334
"k8s.io/autoscaler/cluster-autoscaler/processors"
3435
"k8s.io/autoscaler/cluster-autoscaler/processors/nodes"
3536
"k8s.io/autoscaler/cluster-autoscaler/simulator"
@@ -76,6 +77,7 @@ type Planner struct {
7677
cc controllerReplicasCalculator
7778
scaleDownSetProcessor nodes.ScaleDownSetProcessor
7879
scaleDownContext *nodes.ScaleDownContext
80+
longestNodeScaleDownT *longestNodeScaleDownTime
7981
}
8082

8183
// New creates a new Planner object.
@@ -91,6 +93,11 @@ func New(context *context.AutoscalingContext, processors *processors.Autoscaling
9193
unneededNodes.LoadFromExistingTaints(context.ListerRegistry, time.Now(), context.AutoscalingOptions.NodeDeletionCandidateTTL)
9294
}
9395

96+
var longestNodeScaleDownTime *longestNodeScaleDownTime
97+
if context.AutoscalingOptions.LongestNodeScaleDownTimeTrackerEnabled {
98+
longestNodeScaleDownTime = newLongestNodeScaleDownTime()
99+
}
100+
94101
return &Planner{
95102
context: context,
96103
unremovableNodes: unremovable.NewNodes(),
@@ -104,6 +111,7 @@ func New(context *context.AutoscalingContext, processors *processors.Autoscaling
104111
scaleDownSetProcessor: processors.ScaleDownSetProcessor,
105112
scaleDownContext: nodes.NewDefaultScaleDownContext(),
106113
minUpdateInterval: minUpdateInterval,
114+
longestNodeScaleDownT: longestNodeScaleDownTime,
107115
}
108116
}
109117

@@ -277,13 +285,16 @@ func (p *Planner) categorizeNodes(podDestinations map[string]bool, scaleDownCand
277285
}
278286
p.nodeUtilizationMap = utilizationMap
279287
timer := time.NewTimer(p.context.ScaleDownSimulationTimeout)
288+
endedPrematurely := false
280289

281290
for i, node := range currentlyUnneededNodeNames {
282291
if timedOut(timer) {
292+
p.processUnneededNodes(currentlyUnneededNodeNames[i:], time.Now(), &endedPrematurely)
283293
klog.Warningf("%d out of %d nodes skipped in scale down simulation due to timeout.", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames))
284294
break
285295
}
286296
if len(removableList)-atomicScaleDownNodesCount >= p.unneededNodesLimit() {
297+
p.processUnneededNodes(currentlyUnneededNodeNames[i:], time.Now(), &endedPrematurely)
287298
klog.V(4).Infof("%d out of %d nodes skipped in scale down simulation: there are already %d unneeded nodes so no point in looking for more. Total atomic scale down nodes: %d", len(currentlyUnneededNodeNames)-i, len(currentlyUnneededNodeNames), len(removableList), atomicScaleDownNodesCount)
288299
break
289300
}
@@ -306,6 +317,7 @@ func (p *Planner) categorizeNodes(podDestinations map[string]bool, scaleDownCand
306317
p.unremovableNodes.AddTimeout(unremovable, unremovableTimeout)
307318
}
308319
}
320+
p.processUnneededNodes(nil, time.Now(), &endedPrematurely)
309321
p.unneededNodes.Update(removableList, p.latestUpdate)
310322
if unremovableCount > 0 {
311323
klog.V(1).Infof("%v nodes found to be unremovable in simulation, will re-check them at %v", unremovableCount, unremovableTimeout)
@@ -435,3 +447,53 @@ func timedOut(timer *time.Timer) bool {
435447
return false
436448
}
437449
}
450+
451+
func (p *Planner) processUnneededNodes(currentlyUnneededNodeNames []string, currentTime time.Time, endedPrematurely *bool) {
452+
// if p.longestNodeScaleDownT is not set or endedPrematurely is already true do not do anything -> LongestNodeScaleDownTime is not enabled
453+
// or we already calculated the longest duration in this iteration
454+
// if endedPrematurely is false -> all unneededNodes were successfully simulated and the longest evaluation time is 0
455+
if p.longestNodeScaleDownT == nil || *endedPrematurely {
456+
return
457+
}
458+
*endedPrematurely = true
459+
p.longestNodeScaleDownT.update(currentlyUnneededNodeNames, currentTime)
460+
}
461+
462+
type longestNodeScaleDownTime struct {
463+
defaultTime time.Time
464+
nodeNamesWithTimeStamps map[string]time.Time
465+
}
466+
467+
func newLongestNodeScaleDownTime() *longestNodeScaleDownTime {
468+
return &longestNodeScaleDownTime{}
469+
}
470+
471+
func (l *longestNodeScaleDownTime) get(nodeName string) time.Time {
472+
if _, ok := l.nodeNamesWithTimeStamps[nodeName]; ok {
473+
return l.nodeNamesWithTimeStamps[nodeName]
474+
}
475+
return l.defaultTime
476+
}
477+
478+
func (l *longestNodeScaleDownTime) update(nodeNames []string, currentTime time.Time) {
479+
// if all nodes were processed we need to report time 0
480+
if nodeNames == nil {
481+
l.nodeNamesWithTimeStamps = make(map[string]time.Time)
482+
metrics.ObserveLongestNodeScaleDownTime(0)
483+
return
484+
}
485+
newNodes := make(map[string]time.Time, len(nodeNames))
486+
l.defaultTime = currentTime
487+
minimumTime := l.defaultTime
488+
for _, nodeName := range nodeNames {
489+
// if a node is not in nodeNamesWithTimeStamps use current time
490+
// if a node is already in nodeNamesWithTimeStamps copy the last value
491+
valueFromPrevIter := l.get(nodeName)
492+
newNodes[nodeName] = valueFromPrevIter
493+
if minimumTime.Compare(valueFromPrevIter) > 0 {
494+
minimumTime = valueFromPrevIter
495+
}
496+
}
497+
l.nodeNamesWithTimeStamps = newNodes
498+
metrics.ObserveLongestNodeScaleDownTime(currentTime.Sub(minimumTime))
499+
}

cluster-autoscaler/core/scaledown/planner/planner_test.go

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,6 +1035,178 @@ func TestNodesToDelete(t *testing.T) {
10351035
}
10361036
}
10371037

1038+
func TestLongestNodeScaleDownTime(t *testing.T) {
1039+
testCases := []struct {
1040+
name string
1041+
timedOutNodesCount int
1042+
nodes int
1043+
unneededNodes1 []string
1044+
unneededNodes2 []string
1045+
run int
1046+
}{
1047+
{
1048+
name: "Test to check the functionality of planner's longestNodeScaleDownT",
1049+
timedOutNodesCount: 4,
1050+
nodes: 6,
1051+
unneededNodes1: []string{"n0", "n1", "n2", "n3"},
1052+
unneededNodes2: []string{"n2", "n3", "n4", "n5"},
1053+
run: 2,
1054+
},
1055+
}
1056+
for _, tc := range testCases {
1057+
tc := tc
1058+
t.Run(tc.name, func(t *testing.T) {
1059+
t.Parallel()
1060+
nodes := make([]*apiv1.Node, tc.nodes)
1061+
for i := 0; i < tc.nodes; i++ {
1062+
nodes[i] = BuildTestNode(fmt.Sprintf("n%d", i), 1000, 10)
1063+
}
1064+
provider := testprovider.NewTestCloudProviderBuilder().Build()
1065+
provider.AddNodeGroup("ng1", 0, 0, 0)
1066+
for _, node := range nodes {
1067+
provider.AddNode("ng1", node)
1068+
}
1069+
context, err := NewScaleTestAutoscalingContext(config.AutoscalingOptions{
1070+
NodeGroupDefaults: config.NodeGroupAutoscalingOptions{
1071+
ScaleDownUnneededTime: 1 * time.Minute,
1072+
},
1073+
ScaleDownSimulationTimeout: 1 * time.Hour,
1074+
MaxScaleDownParallelism: 10,
1075+
LongestNodeScaleDownTimeTrackerEnabled: true,
1076+
}, &fake.Clientset{}, nil, provider, nil, nil)
1077+
assert.NoError(t, err)
1078+
clustersnapshot.InitializeClusterSnapshotOrDie(t, context.ClusterSnapshot, nodes, nil)
1079+
deleteOptions := options.NodeDeleteOptions{}
1080+
p := New(&context, processorstest.NewTestProcessors(&context), deleteOptions, nil)
1081+
1082+
var start time.Time
1083+
var timestamp time.Time
1084+
1085+
// take nodes "n0" - "n3" as unneeded
1086+
unneededNodeNames := tc.unneededNodes1
1087+
p.longestNodeScaleDownT.update(unneededNodeNames, timestamp)
1088+
for i := 0; i < tc.run; i++ {
1089+
timestamp = timestamp.Add(1 * time.Second)
1090+
// try to update the map for unneeded nodes with greater ts than the one already present
1091+
p.longestNodeScaleDownT.update(unneededNodeNames, timestamp)
1092+
assert.Equal(t, len(p.longestNodeScaleDownT.nodeNamesWithTimeStamps), tc.timedOutNodesCount)
1093+
for _, val := range p.longestNodeScaleDownT.nodeNamesWithTimeStamps {
1094+
// check that timestamp for all unneeded nodes is still 0s
1095+
assert.Equal(t, val, start)
1096+
}
1097+
}
1098+
// take nodes "n2" - "n5" as unneeded
1099+
unneededNodeNames = tc.unneededNodes2
1100+
// timestamp is 2s now
1101+
p.longestNodeScaleDownT.update(unneededNodeNames, timestamp)
1102+
// check that for n0 and n1 we will get the default time, for n2 and n3 - start time, and for n4 and n5 - current ts
1103+
assert.Equal(t, p.longestNodeScaleDownT.get("n0"), p.longestNodeScaleDownT.defaultTime)
1104+
assert.Equal(t, p.longestNodeScaleDownT.get("n1"), p.longestNodeScaleDownT.defaultTime)
1105+
assert.Equal(t, p.longestNodeScaleDownT.get("n2"), start)
1106+
assert.Equal(t, p.longestNodeScaleDownT.get("n3"), start)
1107+
assert.Equal(t, p.longestNodeScaleDownT.get("n4"), timestamp)
1108+
assert.Equal(t, p.longestNodeScaleDownT.get("n5"), timestamp)
1109+
})
1110+
}
1111+
}
1112+
1113+
func TestLongestNodeScaleDownTimeWithTimeout(t *testing.T) {
1114+
testCases := []struct {
1115+
name string
1116+
nodes []*apiv1.Node
1117+
actuationStatus *fakeActuationStatus
1118+
eligible []string
1119+
maxParallel int
1120+
isSimulationTimeout bool
1121+
unprocessedNodes int
1122+
isFlagEnabled bool
1123+
}{
1124+
{
1125+
name: "Unneeded node limit is exceeded",
1126+
nodes: []*apiv1.Node{
1127+
BuildTestNode("n1", 1000, 10),
1128+
BuildTestNode("n2", 1000, 10),
1129+
BuildTestNode("n3", 1000, 10),
1130+
},
1131+
actuationStatus: &fakeActuationStatus{},
1132+
eligible: []string{"n1", "n2"},
1133+
maxParallel: 0,
1134+
isSimulationTimeout: false,
1135+
// maxParallel=0 forces p.unneededNodesLimit() to be 0, so we will break in the second check inside p.categorizeNodes() right away
1136+
unprocessedNodes: 2,
1137+
isFlagEnabled: true,
1138+
},
1139+
{
1140+
name: "Simulation timeout is hit",
1141+
nodes: []*apiv1.Node{
1142+
BuildTestNode("n1", 1000, 10),
1143+
BuildTestNode("n2", 1000, 10),
1144+
BuildTestNode("n3", 1000, 10),
1145+
},
1146+
actuationStatus: &fakeActuationStatus{},
1147+
eligible: []string{"n1", "n2"},
1148+
maxParallel: 1,
1149+
isSimulationTimeout: true,
1150+
// first node will be deleted and for the second timeout will be triggered
1151+
unprocessedNodes: 1,
1152+
isFlagEnabled: true,
1153+
},
1154+
{
1155+
name: "longestLastScaleDownEvalDuration flag is disabled",
1156+
nodes: []*apiv1.Node{
1157+
BuildTestNode("n1", 1000, 10),
1158+
BuildTestNode("n2", 1000, 10),
1159+
BuildTestNode("n3", 1000, 10),
1160+
},
1161+
actuationStatus: &fakeActuationStatus{},
1162+
eligible: []string{"n1", "n2"},
1163+
maxParallel: 1,
1164+
isSimulationTimeout: false,
1165+
isFlagEnabled: false,
1166+
},
1167+
}
1168+
for _, tc := range testCases {
1169+
tc := tc
1170+
t.Run(tc.name, func(t *testing.T) {
1171+
t.Parallel()
1172+
registry := kube_util.NewListerRegistry(nil, nil, nil, nil, nil, nil, nil, nil, nil)
1173+
provider := testprovider.NewTestCloudProviderBuilder().Build()
1174+
provider.AddNodeGroup("ng1", 0, 0, 0)
1175+
for _, node := range tc.nodes {
1176+
provider.AddNode("ng1", node)
1177+
}
1178+
context, err := NewScaleTestAutoscalingContext(config.AutoscalingOptions{
1179+
NodeGroupDefaults: config.NodeGroupAutoscalingOptions{
1180+
ScaleDownUnneededTime: 10 * time.Minute,
1181+
},
1182+
ScaleDownSimulationTimeout: 1 * time.Second,
1183+
MaxScaleDownParallelism: tc.maxParallel,
1184+
LongestNodeScaleDownTimeTrackerEnabled: tc.isFlagEnabled,
1185+
}, &fake.Clientset{}, registry, provider, nil, nil)
1186+
assert.NoError(t, err)
1187+
clustersnapshot.InitializeClusterSnapshotOrDie(t, context.ClusterSnapshot, tc.nodes, nil)
1188+
deleteOptions := options.NodeDeleteOptions{}
1189+
p := New(&context, processorstest.NewTestProcessors(&context), deleteOptions, nil)
1190+
p.eligibilityChecker = &fakeEligibilityChecker{eligible: asMap(tc.eligible)}
1191+
if tc.isSimulationTimeout {
1192+
context.AutoscalingOptions.ScaleDownSimulationTimeout = 1 * time.Second
1193+
rs := &fakeRemovalSimulator{
1194+
nodes: tc.nodes,
1195+
sleep: 2 * time.Second,
1196+
}
1197+
p.rs = rs
1198+
}
1199+
assert.NoError(t, p.UpdateClusterState(tc.nodes, tc.nodes, &fakeActuationStatus{}, time.Now()))
1200+
if !tc.isFlagEnabled {
1201+
// if flag is disabled p.longestNodeScaleDownT is not initialized
1202+
assert.Nil(t, p.longestNodeScaleDownT)
1203+
} else {
1204+
assert.Equal(t, len(p.longestNodeScaleDownT.nodeNamesWithTimeStamps), tc.unprocessedNodes)
1205+
}
1206+
})
1207+
}
1208+
}
1209+
10381210
func sizedNodeGroup(id string, size int, atomic bool) cloudprovider.NodeGroup {
10391211
ng := testprovider.NewTestNodeGroup(id, 10000, 0, size, true, false, "n1-standard-2", nil, nil)
10401212
ng.SetOptions(&config.NodeGroupAutoscalingOptions{

cluster-autoscaler/metrics/metrics.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,14 @@ var (
425425
Buckets: k8smetrics.ExponentialBuckets(1, 2, 6), // 1, 2, 4, ..., 32
426426
}, []string{"instance_type", "cpu_count", "namespace_count"},
427427
)
428+
429+
longestLastScaleDownEvalDuration = k8smetrics.NewGauge(
430+
&k8smetrics.GaugeOpts{
431+
Namespace: caNamespace,
432+
Name: "longest_scale_down_eval",
433+
Help: "Longest node evaluation time during ScaleDown.",
434+
},
435+
)
428436
)
429437

430438
// RegisterAll registers all metrics.
@@ -461,6 +469,7 @@ func RegisterAll(emitPerNodeGroupMetrics bool) {
461469
legacyregistry.MustRegister(nodeTaintsCount)
462470
legacyregistry.MustRegister(inconsistentInstancesMigsCount)
463471
legacyregistry.MustRegister(binpackingHeterogeneity)
472+
legacyregistry.MustRegister(longestLastScaleDownEvalDuration)
464473

465474
if emitPerNodeGroupMetrics {
466475
legacyregistry.MustRegister(nodesGroupMinNodes)
@@ -748,3 +757,11 @@ func UpdateInconsistentInstancesMigsCount(migCount int) {
748757
func ObserveBinpackingHeterogeneity(instanceType, cpuCount, namespaceCount string, pegCount int) {
749758
binpackingHeterogeneity.WithLabelValues(instanceType, cpuCount, namespaceCount).Observe(float64(pegCount))
750759
}
760+
761+
// ObserveLongestNodeScaleDownTime records the longest time that passed from the first leaving a node unprocessed till now.
762+
// If a node is unneeded, but unprocessed consecutively multiple times, we store only the earliest timestamp.
763+
// Here we report the difference between current time and the earliest time among all unprocessed nodes in current ScaleDown iteration
764+
// If we never timedOut in categorizeNodes() or never exceeded p.unneededNodesLimit(), this value will be 0
765+
func ObserveLongestNodeScaleDownTime(duration time.Duration) {
766+
longestLastScaleDownEvalDuration.Set(float64(duration))
767+
}

0 commit comments

Comments
 (0)