-
Notifications
You must be signed in to change notification settings - Fork 38.8k
/
indexed_job_utils.go
529 lines (485 loc) · 17.5 KB
/
indexed_job_utils.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
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
/*
Copyright 2021 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 job
import (
"fmt"
"math"
"sort"
"strconv"
"strings"
batch "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/storage/names"
"k8s.io/apiserver/pkg/util/feature"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/controller"
"k8s.io/kubernetes/pkg/features"
)
const (
completionIndexEnvName = "JOB_COMPLETION_INDEX"
unknownCompletionIndex = -1
)
func isIndexedJob(job *batch.Job) bool {
return job.Spec.CompletionMode != nil && *job.Spec.CompletionMode == batch.IndexedCompletion
}
func hasBackoffLimitPerIndex(job *batch.Job) bool {
return feature.DefaultFeatureGate.Enabled(features.JobBackoffLimitPerIndex) && job.Spec.BackoffLimitPerIndex != nil
}
type interval struct {
First int
Last int
}
type orderedIntervals []interval
// calculateSucceededIndexes returns the old and new list of succeeded indexes
// in compressed format (intervals).
// The old list is solely based off .status.completedIndexes, but returns an
// empty list if this Job is not tracked with finalizers. The new list includes
// the indexes that succeeded since the last sync.
func calculateSucceededIndexes(logger klog.Logger, job *batch.Job, pods []*v1.Pod) (orderedIntervals, orderedIntervals) {
prevIntervals := parseIndexesFromString(logger, job.Status.CompletedIndexes, int(*job.Spec.Completions))
newSucceeded := sets.New[int]()
for _, p := range pods {
ix := getCompletionIndex(p.Annotations)
// Succeeded Pod with valid index and, if tracking with finalizers,
// has a finalizer (meaning that it is not counted yet).
if p.Status.Phase == v1.PodSucceeded && ix != unknownCompletionIndex && ix < int(*job.Spec.Completions) && hasJobTrackingFinalizer(p) {
newSucceeded.Insert(ix)
}
}
// List returns the items of the set in order.
result := prevIntervals.withOrderedIndexes(sets.List(newSucceeded))
return prevIntervals, result
}
// calculateFailedIndexes returns the list of failed indexes in compressed
// format (intervals). The list includes indexes already present in
// .status.failedIndexes and indexes that failed since the last sync.
func calculateFailedIndexes(logger klog.Logger, job *batch.Job, pods []*v1.Pod) *orderedIntervals {
var prevIntervals orderedIntervals
if job.Status.FailedIndexes != nil {
prevIntervals = parseIndexesFromString(logger, *job.Status.FailedIndexes, int(*job.Spec.Completions))
}
newFailed := sets.New[int]()
for _, p := range pods {
ix := getCompletionIndex(p.Annotations)
// Failed Pod with valid index and has a finalizer (meaning that it is not counted yet).
if ix != unknownCompletionIndex && ix < int(*job.Spec.Completions) && hasJobTrackingFinalizer(p) && isIndexFailed(logger, job, p) {
newFailed.Insert(ix)
}
}
// List returns the items of the set in order.
result := prevIntervals.withOrderedIndexes(sets.List(newFailed))
return &result
}
func isIndexFailed(logger klog.Logger, job *batch.Job, pod *v1.Pod) bool {
isPodFailedCounted := false
if isPodFailed(pod, job) {
if feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) && job.Spec.PodFailurePolicy != nil {
_, countFailed, action := matchPodFailurePolicy(job.Spec.PodFailurePolicy, pod)
if action != nil && *action == batch.PodFailurePolicyActionFailIndex {
return true
}
isPodFailedCounted = countFailed
} else {
isPodFailedCounted = true
}
}
return isPodFailedCounted && getIndexFailureCount(logger, pod) >= *job.Spec.BackoffLimitPerIndex
}
// withOrderedIndexes returns a new list of ordered intervals that contains
// the newIndexes, provided in increasing order.
func (oi orderedIntervals) withOrderedIndexes(newIndexes []int) orderedIntervals {
newIndexIntervals := make(orderedIntervals, len(newIndexes))
for i, newIndex := range newIndexes {
newIndexIntervals[i] = interval{newIndex, newIndex}
}
return oi.merge(newIndexIntervals)
}
// with returns a new list of ordered intervals that contains the newOrderedIntervals.
func (oi orderedIntervals) merge(newOi orderedIntervals) orderedIntervals {
var result orderedIntervals
i := 0
j := 0
var lastInterval *interval
appendOrMergeWithLastInterval := func(thisInterval interval) {
if lastInterval == nil || thisInterval.First > lastInterval.Last+1 {
result = append(result, thisInterval)
lastInterval = &result[len(result)-1]
} else if lastInterval.Last < thisInterval.Last {
lastInterval.Last = thisInterval.Last
}
}
for i < len(oi) && j < len(newOi) {
if oi[i].First < newOi[j].First {
appendOrMergeWithLastInterval(oi[i])
i++
} else {
appendOrMergeWithLastInterval(newOi[j])
j++
}
}
for i < len(oi) {
appendOrMergeWithLastInterval(oi[i])
i++
}
for j < len(newOi) {
appendOrMergeWithLastInterval(newOi[j])
j++
}
return result
}
// total returns number of indexes contained in the intervals.
func (oi orderedIntervals) total() int {
var count int
for _, iv := range oi {
count += iv.Last - iv.First + 1
}
return count
}
func (oi orderedIntervals) String() string {
var builder strings.Builder
for _, v := range oi {
if builder.Len() > 0 {
builder.WriteRune(',')
}
builder.WriteString(strconv.Itoa(v.First))
if v.Last > v.First {
if v.Last == v.First+1 {
builder.WriteRune(',')
} else {
builder.WriteRune('-')
}
builder.WriteString(strconv.Itoa(v.Last))
}
}
return builder.String()
}
func (oi orderedIntervals) has(ix int) bool {
lo := 0
hi := len(oi)
// Invariant: oi[hi].Last >= ix
for hi > lo {
mid := lo + (hi-lo)/2
if oi[mid].Last >= ix {
hi = mid
} else {
lo = mid + 1
}
}
if hi == len(oi) {
return false
}
return oi[hi].First <= ix
}
func parseIndexesFromString(logger klog.Logger, indexesStr string, completions int) orderedIntervals {
if indexesStr == "" {
return nil
}
var result orderedIntervals
var lastInterval *interval
for _, intervalStr := range strings.Split(indexesStr, ",") {
limitsStr := strings.Split(intervalStr, "-")
var inter interval
var err error
inter.First, err = strconv.Atoi(limitsStr[0])
if err != nil {
logger.Info("Corrupted indexes interval, ignoring", "interval", intervalStr, "err", err)
continue
}
if inter.First >= completions {
break
}
if len(limitsStr) > 1 {
inter.Last, err = strconv.Atoi(limitsStr[1])
if err != nil {
logger.Info("Corrupted indexes interval, ignoring", "interval", intervalStr, "err", err)
continue
}
if inter.Last >= completions {
inter.Last = completions - 1
}
} else {
inter.Last = inter.First
}
if lastInterval != nil && lastInterval.Last == inter.First-1 {
lastInterval.Last = inter.Last
} else {
result = append(result, inter)
lastInterval = &result[len(result)-1]
}
}
return result
}
// firstPendingIndexes returns `count` indexes less than `completions` that are
// not covered by `activePods`, `succeededIndexes` or `failedIndexes`.
// In cases of PodReplacementPolicy as Failed we will include `terminatingPods` in this list.
func firstPendingIndexes(jobCtx *syncJobCtx, count, completions int) []int {
if count == 0 {
return nil
}
active := getIndexes(jobCtx.activePods)
result := make([]int, 0, count)
nonPending := jobCtx.succeededIndexes.withOrderedIndexes(sets.List(active))
if onlyReplaceFailedPods(jobCtx.job) {
terminating := getIndexes(controller.FilterTerminatingPods(jobCtx.pods))
nonPending = nonPending.withOrderedIndexes(sets.List(terminating))
}
if jobCtx.failedIndexes != nil {
nonPending = nonPending.merge(*jobCtx.failedIndexes)
}
// The following algorithm is bounded by len(nonPending) and count.
candidate := 0
for _, sInterval := range nonPending {
for ; candidate < completions && len(result) < count && candidate < sInterval.First; candidate++ {
result = append(result, candidate)
}
if candidate < sInterval.Last+1 {
candidate = sInterval.Last + 1
}
}
for ; candidate < completions && len(result) < count; candidate++ {
result = append(result, candidate)
}
return result
}
// Returns the list of indexes corresponding to the set of pods
func getIndexes(pods []*v1.Pod) sets.Set[int] {
result := sets.New[int]()
for _, p := range pods {
ix := getCompletionIndex(p.Annotations)
if ix != unknownCompletionIndex {
result.Insert(ix)
}
}
return result
}
// appendDuplicatedIndexPodsForRemoval scans active `pods` for duplicated
// completion indexes. For each index, it selects n-1 pods for removal, where n
// is the number of repetitions. The pods to be removed are appended to `rm`,
// while the remaining pods are appended to `left`.
// All pods that don't have a completion index are appended to `rm`.
// All pods with index not in valid range are appended to `rm`.
func appendDuplicatedIndexPodsForRemoval(rm, left, pods []*v1.Pod, completions int) ([]*v1.Pod, []*v1.Pod) {
sort.Sort(byCompletionIndex(pods))
lastIndex := unknownCompletionIndex
firstRepeatPos := 0
countLooped := 0
for i, p := range pods {
ix := getCompletionIndex(p.Annotations)
if ix >= completions {
rm = append(rm, pods[i:]...)
break
}
if ix != lastIndex {
rm, left = appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods[firstRepeatPos:i], lastIndex)
firstRepeatPos = i
lastIndex = ix
}
countLooped += 1
}
return appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods[firstRepeatPos:countLooped], lastIndex)
}
// getPodsWithDelayedDeletionPerIndex returns the pod which removal is delayed
// in order to await for recreation. This map is used when BackoffLimitPerIndex
// is enabled to delay pod finalizer removal, and thus pod deletion, until the
// replacement pod is created. The pod deletion is delayed so that the
// replacement pod can have the batch.kubernetes.io/job-index-failure-count
// annotation set properly keeping track of the number of failed pods within
// the index.
func getPodsWithDelayedDeletionPerIndex(logger klog.Logger, jobCtx *syncJobCtx) map[int]*v1.Pod {
// the failed pods corresponding to currently active indexes can be safely
// deleted as the failure count annotation is present in the currently
// active pods.
activeIndexes := getIndexes(jobCtx.activePods)
podsWithDelayedDeletionPerIndex := make(map[int]*v1.Pod)
getValidPodsWithFilter(jobCtx, nil, func(p *v1.Pod) bool {
if isPodFailed(p, jobCtx.job) {
if ix := getCompletionIndex(p.Annotations); ix != unknownCompletionIndex && ix < int(*jobCtx.job.Spec.Completions) {
if jobCtx.succeededIndexes.has(ix) || jobCtx.failedIndexes.has(ix) || activeIndexes.Has(ix) {
return false
}
if lastPodWithDelayedDeletion, ok := podsWithDelayedDeletionPerIndex[ix]; ok {
if getIndexAbsoluteFailureCount(logger, lastPodWithDelayedDeletion) <= getIndexAbsoluteFailureCount(logger, p) && !getFinishedTime(p).Before(getFinishedTime(lastPodWithDelayedDeletion)) {
podsWithDelayedDeletionPerIndex[ix] = p
}
} else {
podsWithDelayedDeletionPerIndex[ix] = p
}
}
}
return false
})
return podsWithDelayedDeletionPerIndex
}
func addIndexFailureCountAnnotation(logger klog.Logger, template *v1.PodTemplateSpec, job *batch.Job, podBeingReplaced *v1.Pod) {
indexFailureCount, indexIgnoredFailureCount := getNewIndexFailureCounts(logger, job, podBeingReplaced)
template.Annotations[batch.JobIndexFailureCountAnnotation] = strconv.Itoa(int(indexFailureCount))
if indexIgnoredFailureCount > 0 {
template.Annotations[batch.JobIndexIgnoredFailureCountAnnotation] = strconv.Itoa(int(indexIgnoredFailureCount))
}
}
// getNewIndexFailureCount returns the value of the index-failure-count
// annotation for the new pod being created
func getNewIndexFailureCounts(logger klog.Logger, job *batch.Job, podBeingReplaced *v1.Pod) (int32, int32) {
if podBeingReplaced != nil {
indexFailureCount := parseIndexFailureCountAnnotation(logger, podBeingReplaced)
indexIgnoredFailureCount := parseIndexFailureIgnoreCountAnnotation(logger, podBeingReplaced)
if feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) && job.Spec.PodFailurePolicy != nil {
_, countFailed, _ := matchPodFailurePolicy(job.Spec.PodFailurePolicy, podBeingReplaced)
if countFailed {
indexFailureCount++
} else {
indexIgnoredFailureCount++
}
} else {
indexFailureCount++
}
return indexFailureCount, indexIgnoredFailureCount
}
return 0, 0
}
func appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods []*v1.Pod, ix int) ([]*v1.Pod, []*v1.Pod) {
if ix == unknownCompletionIndex {
rm = append(rm, pods...)
return rm, left
}
if len(pods) == 1 {
left = append(left, pods[0])
return rm, left
}
sort.Sort(controller.ActivePods(pods))
rm = append(rm, pods[:len(pods)-1]...)
left = append(left, pods[len(pods)-1])
return rm, left
}
func getCompletionIndex(annotations map[string]string) int {
if annotations == nil {
return unknownCompletionIndex
}
v, ok := annotations[batch.JobCompletionIndexAnnotation]
if !ok {
return unknownCompletionIndex
}
i, err := strconv.Atoi(v)
if err != nil {
return unknownCompletionIndex
}
if i < 0 {
return unknownCompletionIndex
}
return i
}
// getIndexFailureCount returns the value of the batch.kubernetes.io/job-index-failure-count
// annotation as int32. It fallbacks to 0 when:
// - there is no annotation - for example the pod was created when the BackoffLimitPerIndex
// feature was temporarily disabled, or the annotation was manually removed by the user,
// - the value of the annotation isn't parsable as int - for example because
// it was set by a malicious user,
// - the value of the annotation is negative or greater by int32 - for example
// because it was set by a malicious user.
func getIndexFailureCount(logger klog.Logger, pod *v1.Pod) int32 {
return parseIndexFailureCountAnnotation(logger, pod)
}
func getIndexAbsoluteFailureCount(logger klog.Logger, pod *v1.Pod) int32 {
return parseIndexFailureCountAnnotation(logger, pod) + parseIndexFailureIgnoreCountAnnotation(logger, pod)
}
func parseIndexFailureCountAnnotation(logger klog.Logger, pod *v1.Pod) int32 {
if value, ok := pod.Annotations[batch.JobIndexFailureCountAnnotation]; ok {
return parseInt32(logger, value)
}
logger.V(3).Info("There is no expected annotation", "annotationKey", batch.JobIndexFailureCountAnnotation, "pod", klog.KObj(pod), "podUID", pod.UID)
return 0
}
func parseIndexFailureIgnoreCountAnnotation(logger klog.Logger, pod *v1.Pod) int32 {
if value, ok := pod.Annotations[batch.JobIndexIgnoredFailureCountAnnotation]; ok {
return parseInt32(logger, value)
}
return 0
}
func parseInt32(logger klog.Logger, vStr string) int32 {
if vInt, err := strconv.Atoi(vStr); err != nil {
logger.Error(err, "Failed to parse the value", "value", vStr)
return 0
} else if vInt < 0 || vInt > math.MaxInt32 {
logger.Info("The value is invalid", "value", vInt)
return 0
} else {
return int32(vInt)
}
}
func addCompletionIndexEnvVariables(template *v1.PodTemplateSpec) {
for i := range template.Spec.InitContainers {
addCompletionIndexEnvVariable(&template.Spec.InitContainers[i])
}
for i := range template.Spec.Containers {
addCompletionIndexEnvVariable(&template.Spec.Containers[i])
}
}
func addCompletionIndexEnvVariable(container *v1.Container) {
for _, v := range container.Env {
if v.Name == completionIndexEnvName {
return
}
}
var fieldPath string
if feature.DefaultFeatureGate.Enabled(features.PodIndexLabel) {
fieldPath = fmt.Sprintf("metadata.labels['%s']", batch.JobCompletionIndexAnnotation)
} else {
fieldPath = fmt.Sprintf("metadata.annotations['%s']", batch.JobCompletionIndexAnnotation)
}
container.Env = append(container.Env, v1.EnvVar{
Name: completionIndexEnvName,
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: fieldPath,
},
},
})
}
func addCompletionIndexAnnotation(template *v1.PodTemplateSpec, index int) {
if template.Annotations == nil {
template.Annotations = make(map[string]string, 1)
}
template.Annotations[batch.JobCompletionIndexAnnotation] = strconv.Itoa(index)
}
func addCompletionIndexLabel(template *v1.PodTemplateSpec, index int) {
if template.Labels == nil {
template.Labels = make(map[string]string, 1)
}
// For consistency, we use the annotation batch.kubernetes.io/job-completion-index for the corresponding label as well.
template.Labels[batch.JobCompletionIndexAnnotation] = strconv.Itoa(index)
}
func podGenerateNameWithIndex(jobName string, index int) string {
appendIndex := "-" + strconv.Itoa(index) + "-"
generateNamePrefix := jobName + appendIndex
if len(generateNamePrefix) > names.MaxGeneratedNameLength {
generateNamePrefix = generateNamePrefix[:names.MaxGeneratedNameLength-len(appendIndex)] + appendIndex
}
return generateNamePrefix
}
type byCompletionIndex []*v1.Pod
func (bci byCompletionIndex) Less(i, j int) bool {
return getCompletionIndex(bci[i].Annotations) < getCompletionIndex(bci[j].Annotations)
}
func (bci byCompletionIndex) Swap(i, j int) {
bci[i], bci[j] = bci[j], bci[i]
}
func (bci byCompletionIndex) Len() int {
return len(bci)
}
func completionModeStr(job *batch.Job) string {
if job.Spec.CompletionMode != nil {
return string(*job.Spec.CompletionMode)
}
return string(batch.NonIndexedCompletion)
}