@@ -3,14 +3,12 @@ package periodic
3
3
import (
4
4
"context"
5
5
"fmt"
6
- "time"
7
6
8
7
batchv1 "k8s.io/api/batch/v1"
9
8
corev1 "k8s.io/api/core/v1"
10
- "k8s.io/apimachinery/pkg/api/errors"
11
9
"k8s.io/apimachinery/pkg/api/resource"
12
10
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
13
- "k8s.io/apimachinery/pkg/util/wait "
11
+ "k8s.io/apimachinery/pkg/watch "
14
12
"k8s.io/client-go/kubernetes"
15
13
)
16
14
@@ -108,19 +106,38 @@ func (j *JobController) CreateGathererJob(ctx context.Context, dataGatherName, i
108
106
return j .kubeClient .BatchV1 ().Jobs (insightsNamespace ).Create (ctx , gj , metav1.CreateOptions {})
109
107
}
110
108
111
- // WaitForJobCompletion polls the Kubernetes API every 20 seconds and checks if the job finished.
112
- func (j * JobController ) WaitForJobCompletion (ctx context.Context , job * batchv1.Job ) error {
113
- return wait .PollUntilContextCancel (ctx , 20 * time .Second , true , func (ctx context.Context ) (done bool , err error ) {
114
- j , err := j .kubeClient .BatchV1 ().Jobs (insightsNamespace ).Get (ctx , job .Name , metav1.GetOptions {})
115
- if errors .IsNotFound (err ) {
116
- return false , err
117
- }
118
- if j .Status .Succeeded > 0 {
119
- return true , nil
120
- }
121
- if j .Status .Failed > 0 {
122
- return true , fmt .Errorf ("job %s failed" , job .Name )
109
+ // WaitForJobCompletion listen the Kubernetes events to check if job finished.
110
+ func (j * JobController ) WaitForJobCompletion (ctx context.Context , jobName string ) error {
111
+ watcher , err := j .kubeClient .BatchV1 ().Jobs (insightsNamespace ).
112
+ Watch (ctx , metav1.ListOptions {FieldSelector : fmt .Sprintf ("metadata.name=%s" , jobName )})
113
+ if err != nil {
114
+ return err
115
+ }
116
+ defer watcher .Stop ()
117
+
118
+ for {
119
+ select {
120
+ case <- ctx .Done ():
121
+ return ctx .Err ()
122
+ case event , ok := <- watcher .ResultChan ():
123
+ if ! ok {
124
+ return fmt .Errorf ("watcher channel was closed unexpectedly" )
125
+ }
126
+
127
+ if event .Type != watch .Modified {
128
+ continue
129
+ }
130
+
131
+ job , ok := event .Object .(* batchv1.Job )
132
+ if ! ok {
133
+ return fmt .Errorf ("failed to cast job event: %v" , event .Object )
134
+ }
135
+ if job .Status .Succeeded > 0 {
136
+ return nil
137
+ }
138
+ if job .Status .Failed > 0 {
139
+ return fmt .Errorf ("job %s failed" , job .Name )
140
+ }
123
141
}
124
- return false , nil
125
- })
142
+ }
126
143
}
0 commit comments