-
Notifications
You must be signed in to change notification settings - Fork 1
/
job.go
89 lines (72 loc) · 2.51 KB
/
job.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
package kube
import (
"fmt"
"time"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
)
// waits for the job to complete
func WaitForJobToSucceeded(client kubernetes.Interface, namespace, jobName string, timeout time.Duration) error {
job, err := client.BatchV1().Jobs(namespace).Get(jobName, metav1.GetOptions{})
if err != nil {
return err
}
options := metav1.ListOptions{FieldSelector: fields.OneTermEqualSelector("metadata.name", job.Name).String()}
w, err := client.BatchV1().Jobs(namespace).Watch(options)
if err != nil {
return err
}
defer w.Stop()
condition := func(event watch.Event) (bool, error) {
job := event.Object.(*batchv1.Job)
return job.Status.Succeeded == 1, nil
}
_, err = watch.Until(timeout, w, condition)
if err == wait.ErrWaitTimeout {
return fmt.Errorf("job %s never succeeded", jobName)
}
return nil
}
// waits for the job to terminate
func WaitForJobToTerminate(client kubernetes.Interface, namespace, jobName string, timeout time.Duration) error {
job, err := client.BatchV1().Jobs(namespace).Get(jobName, metav1.GetOptions{})
if err != nil {
return err
}
options := metav1.ListOptions{FieldSelector: fields.OneTermEqualSelector("metadata.name", job.Name).String()}
w, err := client.BatchV1().Jobs(namespace).Watch(options)
if err != nil {
return err
}
defer w.Stop()
condition := func(event watch.Event) (bool, error) {
job := event.Object.(*batchv1.Job)
return job.Status.Succeeded == 1 || job.Status.Failed == 1, nil
}
_, err = watch.Until(timeout, w, condition)
if err == wait.ErrWaitTimeout {
return fmt.Errorf("job %s never terminated", jobName)
}
return nil
}
// IsJobSucceeded returns true if the job completed and did not fail
func IsJobSucceeded(job *batchv1.Job) bool {
return IsJobFinished(job) && job.Status.Succeeded > 0
}
// IsJobFinished returns true if the job has completed
func IsJobFinished(job *batchv1.Job) bool {
BackoffLimit := job.Spec.BackoffLimit
return job.Status.CompletionTime != nil || (job.Status.Active == 0 && BackoffLimit != nil && job.Status.Failed >= *BackoffLimit)
}
func DeleteJob(client kubernetes.Interface, namespace, name string) error {
err := client.BatchV1().Jobs(namespace).Delete(name, metav1.NewDeleteOptions(0))
if err != nil {
return fmt.Errorf("error deleting job %s. error: %v", name, err)
return fmt.Errorf("job %s never succeeded", name)
}
return nil
}