-
Notifications
You must be signed in to change notification settings - Fork 126
/
pod_util.go
367 lines (299 loc) · 8.62 KB
/
pod_util.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
package util
import (
"errors"
"fmt"
"strconv"
"time"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"github.com/armadaproject/armada/internal/common/util"
"github.com/armadaproject/armada/internal/executor/domain"
)
var managedPodSelector labels.Selector
func init() {
managedPodSelector = createLabelSelectorForManagedPods()
}
func HasIngress(pod *v1.Pod) bool {
value, exists := pod.Annotations[domain.HasIngress]
return exists && value == "true"
}
func GetExpectedNumberOfAssociatedServices(pod *v1.Pod) int {
value, exists := pod.Annotations[domain.AssociatedServicesCount]
if !exists {
return 0
}
numberOfAssociatedServices, err := strconv.Atoi(value)
if err != nil {
log.Warnf("Failed to extract the expected number of associated services because %s", err)
return 0
}
return numberOfAssociatedServices
}
func GetExpectedNumberOfAssociatedIngresses(pod *v1.Pod) int {
value, exists := pod.Annotations[domain.AssociatedIngressesCount]
if !exists {
return 0
}
numberOfAssociatedIngresses, err := strconv.Atoi(value)
if err != nil {
log.Warnf("Failed to extract the expected number of associated ingresses because %s", err)
return 0
}
return numberOfAssociatedIngresses
}
func IsInTerminalState(pod *v1.Pod) bool {
podPhase := pod.Status.Phase
if podPhase == v1.PodSucceeded || podPhase == v1.PodFailed {
return true
}
return false
}
func IsManagedPod(pod *v1.Pod) bool {
_, ok := pod.Labels[domain.JobId]
return ok
}
func GetManagedPodSelector() labels.Selector {
return managedPodSelector.DeepCopySelector()
}
func createLabelSelectorForManagedPods() labels.Selector {
jobIdExistsRequirement, err := labels.NewRequirement(domain.JobId, selection.Exists, []string{})
if err != nil {
panic(err)
}
selector := labels.NewSelector().Add(*jobIdExistsRequirement)
return selector
}
func ExtractNames(pods []*v1.Pod) []string {
podNames := make([]string, 0, len(pods))
for _, pod := range pods {
podNames = append(podNames, pod.Name)
}
return podNames
}
func ExtractJobIds(pods []*v1.Pod) []string {
jobIds := make([]string, 0, len(pods))
for _, pod := range pods {
if jobId := ExtractJobId(pod); jobId != "" {
jobIds = append(jobIds, jobId)
}
}
return jobIds
}
func ExtractJobId(pod *v1.Pod) string {
return pod.Labels[domain.JobId]
}
func ExtractQueue(pod *v1.Pod) string {
return pod.Labels[domain.Queue]
}
func ExtractJobSet(pod *v1.Pod) string {
return pod.Annotations[domain.JobSetId]
}
func ExtractJobRunIds(pods []*v1.Pod) []string {
runIds := make([]string, 0, len(pods))
for _, pod := range pods {
if runId := ExtractJobRunId(pod); runId != "" {
runIds = append(runIds, runId)
}
}
return runIds
}
func ExtractJobRunId(pod *v1.Pod) string {
return pod.Labels[domain.JobRunId]
}
func ExtractPodNumber(pod *v1.Pod) int {
i, _ := strconv.Atoi(pod.Labels[domain.PodNumber])
return i
}
func ExtractPodKey(pod *v1.Pod) string {
return fmt.Sprintf("%s_%d", ExtractJobId(pod), ExtractPodNumber(pod))
}
func FilterCompletedPods(pods []*v1.Pod) []*v1.Pod {
completedPods := make([]*v1.Pod, 0, len(pods))
for _, pod := range pods {
if IsInTerminalState(pod) {
completedPods = append(completedPods, pod)
}
}
return completedPods
}
func FilterNonCompletedPods(pods []*v1.Pod) []*v1.Pod {
activePods := make([]*v1.Pod, 0)
for _, pod := range pods {
if !IsInTerminalState(pod) {
activePods = append(activePods, pod)
}
}
return activePods
}
func FilterPodsWithPhase(pods []*v1.Pod, podPhase v1.PodPhase) []*v1.Pod {
podsInPhase := make([]*v1.Pod, 0)
for _, pod := range pods {
if pod.Status.Phase == podPhase {
podsInPhase = append(podsInPhase, pod)
}
}
return podsInPhase
}
func IsReportingPhaseRequired(podPhase v1.PodPhase) bool {
return podPhase != v1.PodPending && podPhase != v1.PodUnknown
}
func MergePodList(list1 []*v1.Pod, list2 []*v1.Pod) []*v1.Pod {
jobIds := ExtractNames(list1)
jobIdsSet := util.StringListToSet(jobIds)
allPods := list1
for _, pod := range list2 {
if !jobIdsSet[pod.Name] {
allPods = append(allPods, pod)
}
}
return allPods
}
func FilterPods(pods []*v1.Pod, filter func(*v1.Pod) bool) []*v1.Pod {
result := make([]*v1.Pod, 0)
for _, pod := range pods {
if filter(pod) {
result = append(result, pod)
}
}
return result
}
func LastStatusChange(pod *v1.Pod) (time.Time, error) {
maxStatusChange := pod.CreationTimestamp.Time
for _, containerStatus := range pod.Status.ContainerStatuses {
if s := containerStatus.State.Running; s != nil {
maxStatusChange = maxTime(maxStatusChange, s.StartedAt.Time)
}
if s := containerStatus.State.Terminated; s != nil {
maxStatusChange = maxTime(maxStatusChange, s.FinishedAt.Time)
}
}
for _, condition := range pod.Status.Conditions {
maxStatusChange = maxTime(maxStatusChange, condition.LastTransitionTime.Time)
}
if maxStatusChange.IsZero() {
return maxStatusChange, errors.New("cannot determine last status change")
}
return maxStatusChange, nil
}
func FindLastContainerStartTime(pod *v1.Pod) time.Time {
// Fallback to pod creation if there is no container
startTime := pod.CreationTimestamp.Time
for _, c := range pod.Status.ContainerStatuses {
if s := c.State.Running; s != nil {
startTime = maxTime(startTime, s.StartedAt.Time)
}
if s := c.State.Terminated; s != nil {
startTime = maxTime(startTime, s.StartedAt.Time)
}
}
return startTime
}
func HasPodBeenInStateForLongerThanGivenDuration(pod *v1.Pod, duration time.Duration) bool {
deadline := time.Now().Add(-duration)
lastStatusChange, err := LastStatusChange(pod)
if err != nil {
log.Errorf("Problem determining last state change for pod %v: %v", pod.Name, err)
return false
}
return lastStatusChange.Before(deadline)
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
func GetPodContainerStatuses(pod *v1.Pod) []v1.ContainerStatus {
containerStatuses := pod.Status.ContainerStatuses
containerStatuses = append(containerStatuses, pod.Status.InitContainerStatuses...)
return containerStatuses
}
func IsMarkedForDeletion(pod *v1.Pod) bool {
_, exists := pod.Annotations[domain.MarkedForDeletion]
return exists
}
func IsReportedDone(pod *v1.Pod) bool {
_, exists := pod.Annotations[domain.JobDoneAnnotation]
return exists
}
func IsReportedPreempted(pod *v1.Pod) bool {
_, exists := pod.Annotations[domain.JobPreemptedAnnotation]
return exists
}
// GetDeletionGracePeriodOrDefault returns the pod's DeletionGracePeriodSeconds seconds (if populated) or the K8s
// default value of 30 seconds (if it isn't)
func GetDeletionGracePeriodOrDefault(pod *v1.Pod) time.Duration {
podGracePeriodSeconds := pod.GetDeletionGracePeriodSeconds()
if podGracePeriodSeconds == nil {
return 30 * time.Second
} else {
return time.Duration(*podGracePeriodSeconds) * time.Second
}
}
func IsPodFinishedAndReported(pod *v1.Pod) bool {
if !IsInTerminalState(pod) ||
!IsReportedDone(pod) ||
!HasCurrentStateBeenReported(pod) {
return false
}
return true
}
func HasCurrentStateBeenReported(pod *v1.Pod) bool {
podPhase := pod.Status.Phase
_, annotationPresent := pod.Annotations[string(podPhase)]
return annotationPresent
}
func CountPodsByPhase(pods []*v1.Pod) map[string]uint32 {
pods = RemoveDuplicates(pods)
result := map[string]uint32{}
for _, pod := range pods {
phase := string(pod.Status.Phase)
if _, present := result[phase]; !present {
result[phase] = 0
}
result[phase]++
}
return result
}
func RemoveDuplicates(pods []*v1.Pod) []*v1.Pod {
podsSet := map[string]*v1.Pod{}
for _, pod := range pods {
if _, present := podsSet[pod.Name]; !present {
podsSet[pod.Name] = pod
}
}
result := make([]*v1.Pod, 0, len(podsSet))
for _, pod := range podsSet {
result = append(result, pod)
}
return result
}
func RemovePodsFromList(list1 []*v1.Pod, list2 []*v1.Pod) []*v1.Pod {
podsToRemove := ExtractNames(list2)
podsToRemoveSet := util.StringListToSet(podsToRemove)
result := make([]*v1.Pod, 0, len(list1))
for _, pod := range list1 {
if _, present := podsToRemoveSet[pod.Name]; !present {
result = append(result, pod)
}
}
return result
}
// GroupByQueue Any pod without a queue label set is excluded from the output
func GroupByQueue(pods []*v1.Pod) map[string][]*v1.Pod {
podsByQueue := map[string][]*v1.Pod{}
for _, pod := range pods {
queue, exists := pod.Labels[domain.Queue]
if !exists {
log.Warnf("Cannot group pod %s/%s by queue as it has no queue set", pod.Namespace, pod.Name)
continue
}
if _, exists := podsByQueue[queue]; !exists {
podsByQueue[queue] = make([]*v1.Pod, 0, 10)
}
podsByQueue[queue] = append(podsByQueue[queue], pod)
}
return podsByQueue
}