-
Notifications
You must be signed in to change notification settings - Fork 82
/
wait.go
90 lines (83 loc) · 1.98 KB
/
wait.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
package cronjobs
import (
"context"
"errors"
"strings"
"time"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
)
func waitJobs(
lg *zap.Logger,
stopc chan struct{},
clientSet *clientset.Clientset,
timeout time.Duration,
interval time.Duration,
namespace string,
jobName string,
targets int,
fieldSelector string,
desiredPodPhase v1.PodPhase,
) (pods []v1.Pod, err error) {
lg.Info("waiting Pod",
zap.String("namespace", namespace),
zap.String("job-name", jobName),
zap.String("field-selector", fieldSelector),
)
retryStart := time.Now()
for time.Now().Sub(retryStart) < timeout {
select {
case <-stopc:
return nil, errors.New("Pod polling aborted")
case <-time.After(interval):
}
// https://github.com/kubernetes/kubernetes/blob/d379ab2697251334774b7bd6f41b26cf39de470d/pkg/apis/batch/v1/conversion.go#L30-L41
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
jobs, err := clientSet.
CoreV1().
Pods(namespace).
List(ctx, metav1.ListOptions{FieldSelector: fieldSelector})
cancel()
if err != nil {
lg.Warn("failed to list Pod", zap.Error(err))
continue
}
pods = jobs.Items
if len(pods) == 0 {
lg.Warn("got an empty list of Pod",
zap.String("namespace", namespace),
zap.String("job-name", jobName),
zap.String("field-selector", fieldSelector),
)
continue
}
count := 0
for _, item := range pods {
jv, ok := item.Labels["job-name"]
match := ok && jv == jobName
if !match {
match = strings.HasPrefix(item.Name, jobName)
}
if !match {
continue
}
if item.Status.Phase != desiredPodPhase {
continue
}
count++
}
if count == targets {
lg.Info("found all targets", zap.Int("target", targets))
break
}
lg.Info("polling",
zap.String("namespace", namespace),
zap.String("job-name", jobName),
zap.Int("count", count),
zap.Int("target", targets),
)
}
return pods, nil
}