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
package scale
import (
"fmt"
"slices"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const HostnameLabel = "kubernetes.io/hostname"
type NodeLoad struct {
Name string
Created time.Time
Held bool
Busy int
Evictable int
Incoming bool
Ready bool
ReadySince time.Time
}
type Placement struct {
Nodes []NodeLoad
Unplaced []time.Time
Unschedulable []Unschedulable
Spread Spread
}
func (p Placement) Load(name string) (NodeLoad, bool) {
for _, n := range p.Nodes {
if n.Name == name {
return n, true
}
}
return NodeLoad{}, false
}
func (p Placement) placing(now time.Time, hold time.Duration) (time.Duration, bool) {
for _, created := range p.Unplaced {
if created.IsZero() {
return 0, true
}
if age := now.Sub(created); age < hold {
return age, true
}
}
return 0, false
}
func ControlledByADaemonSet(p *corev1.Pod) bool {
c := metav1.GetControllerOf(p)
return c != nil && c.Kind == KindDaemonSet
}
func MirrorPod(p *corev1.Pod) bool {
_, ok := p.Annotations[corev1.MirrorPodAnnotationKey]
return ok
}
func FollowsTheNodes(p *corev1.Pod) bool {
return ControlledByADaemonSet(p) || MirrorPod(p)
}
func live(p *corev1.Pod) bool {
switch p.Status.Phase {
case corev1.PodPending, corev1.PodRunning, corev1.PodUnknown:
return true
}
return false
}
func Loads(nodes []corev1.Node, o Observation, replicaSets []appsv1.ReplicaSet, b Baseline) Placement {
ours := baselineWorkloads(o, b)
deploymentOf := deploymentsOfReplicaSets(replicaSets)
byName := map[string]*NodeLoad{}
out := Placement{Nodes: make([]NodeLoad, 0, len(nodes))}
for i := range nodes {
ready, since := NodeReady(&nodes[i])
out.Nodes = append(out.Nodes, NodeLoad{Name: nodes[i].Name, Created: nodes[i].CreationTimestamp.Time,
Ready: ready, ReadySince: since})
}
var workload []*corev1.Pod
for i := range out.Nodes {
byName[out.Nodes[i].Name] = &out.Nodes[i]
}
for i := range o.Pods {
p := &o.Pods[i]
if !live(p) || FollowsTheNodes(p) {
continue
}
baseline := AppliedByTheControlPlane(p.ObjectMeta)
if k, ok := workloadOf(p, deploymentOf); ok && ours[k] {
baseline = true
}
if !baseline && p.DeletionTimestamp == nil {
workload = append(workload, p)
}
if p.Spec.NodeName != "" {
n, ok := byName[p.Spec.NodeName]
if !ok {
continue
}
if baseline {
n.Evictable++
} else {
n.Busy++
}
continue
}
if baseline || p.Status.Phase != corev1.PodPending {
continue
}
if target := destinedFor(p); target != "" {
if n, ok := byName[target]; ok {
n.Incoming = true
continue
}
}
out.Unplaced = append(out.Unplaced, p.CreationTimestamp.Time)
if u, ok := unschedulable(p); ok {
out.Unschedulable = append(out.Unschedulable, u)
}
}
out.Spread = spreadOf(workload)
return out
}
func destinedFor(p *corev1.Pod) string {
if p.Status.NominatedNodeName != "" {
return p.Status.NominatedNodeName
}
if h := p.Spec.NodeSelector[HostnameLabel]; h != "" {
return h
}
a := p.Spec.Affinity
if a == nil || a.NodeAffinity == nil || a.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
return ""
}
for _, term := range a.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms {
for _, r := range term.MatchExpressions {
if r.Key == HostnameLabel && r.Operator == corev1.NodeSelectorOpIn && len(r.Values) == 1 {
return r.Values[0]
}
}
for _, r := range term.MatchFields {
if r.Key == "metadata.name" && r.Operator == corev1.NodeSelectorOpIn && len(r.Values) == 1 {
return r.Values[0]
}
}
}
return ""
}
func baselineWorkloads(o Observation, b Baseline) map[WorkloadKey]bool {
out := map[WorkloadKey]bool{}
for _, d := range o.Deployments {
k := WorkloadKey{Kind: KindDeployment, Namespace: d.Namespace, Name: d.Name}
if AppliedByTheControlPlane(d.ObjectMeta) || b.Holds(k, d.Spec) {
out[k] = true
}
}
for _, s := range o.StatefulSets {
k := WorkloadKey{Kind: KindStatefulSet, Namespace: s.Namespace, Name: s.Name}
if AppliedByTheControlPlane(s.ObjectMeta) || b.Holds(k, s.Spec) {
out[k] = true
}
}
for _, j := range o.Jobs {
k := WorkloadKey{Kind: KindJob, Namespace: j.Namespace, Name: j.Name}
if AppliedByTheControlPlane(j.ObjectMeta) || b.Holds(k, j.Spec) {
out[k] = true
}
}
return out
}
func deploymentsOfReplicaSets(replicaSets []appsv1.ReplicaSet) map[WorkloadKey]WorkloadKey {
out := map[WorkloadKey]WorkloadKey{}
for i := range replicaSets {
rs := &replicaSets[i]
if c := metav1.GetControllerOf(rs); c != nil && c.Kind == KindDeployment {
out[WorkloadKey{Kind: KindReplicaSet, Namespace: rs.Namespace, Name: rs.Name}] =
WorkloadKey{Kind: KindDeployment, Namespace: rs.Namespace, Name: c.Name}
}
}
return out
}
func (n NodeLoad) idle() bool {
return n.Busy == 0 && !n.Incoming
}
func nodeClocks(p Placement, before map[string]time.Time, now time.Time) map[string]time.Time {
out := make(map[string]time.Time, len(p.Nodes))
for _, n := range p.Nodes {
if !n.idle() {
continue
}
if since, ok := before[n.Name]; ok {
out[n.Name] = since
continue
}
out[n.Name] = now
}
return out
}
func restartedClocks(clocks map[string]time.Time, released string, now time.Time) map[string]time.Time {
out := make(map[string]time.Time, len(clocks))
for name := range clocks {
if name == released {
continue
}
out[name] = now
}
return out
}
func releasable(p Placement, clocks map[string]time.Time, now time.Time, hold time.Duration) []NodeLoad {
var out []NodeLoad
for _, n := range p.Nodes {
if !n.Held || !n.idle() {
continue
}
since, ok := clocks[n.Name]
if !ok || now.Sub(since) < hold {
continue
}
out = append(out, n)
}
slices.SortFunc(out, func(a, b NodeLoad) int {
switch {
case a.Evictable != b.Evictable:
return a.Evictable - b.Evictable
case !a.Created.Equal(b.Created):
return b.Created.Compare(a.Created)
}
if a.Name < b.Name {
return -1
}
if a.Name > b.Name {
return 1
}
return 0
})
return out
}
func scaleIn(o Observation, st State, now time.Time, opts Options, target int, clocks map[string]time.Time) Decision {
hold := opts.hold()
keep := Decision{Action: None, Nodes: st.Nodes, Intent: true, NodeIdleSince: clocks}
if age, placing := o.Placement.placing(now, hold); placing {
keep.Reason = fmt.Sprintf("intent, and %d nodes are counted for a target of %d, and a pod "+
"created %s ago is Pending with no node yet: the scheduler may place it on any idle "+
"node, so no node is released until it is placed or has waited out the %s hold",
st.Nodes, target, age.Round(time.Second), hold)
return keep
}
candidates := releasable(o.Placement, clocks, now, hold)
if len(candidates) == 0 {
keep.Reason = fmt.Sprintf("intent, and %d nodes are counted for a target of %d, and no "+
"node this provider holds has held nothing beyond the baseline for the %s hold",
st.Nodes, target, hold)
return keep
}
pick := candidates[0]
return Decision{
Action: Release, Nodes: st.Nodes - 1, Intent: true, Release: pick.Name,
Idle: now.Sub(clocks[pick.Name]), NodeIdleSince: clocks,
Reason: fmt.Sprintf("intent, and %d nodes are counted for a target of %d; %s has held "+
"nothing beyond the baseline for %s, past the %s hold, and is the emptiest and newest "+
"of %d such nodes, so it alone is released this hold",
st.Nodes, target, pick.Name, now.Sub(clocks[pick.Name]).Round(time.Second), hold,
len(candidates)),
}
}