-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd_wait.go
89 lines (83 loc) · 1.99 KB
/
cmd_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
package main
import (
"fmt"
"os"
"time"
v1batch "k8s.io/api/batch/v1"
apiv1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
)
func cmdWait(args []string, config *appConfig) {
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "USAGE: %s jobname\n", os.Args[0])
os.Exit(1)
}
jobName := args[0]
namespace := "default"
if config.namespace != "" {
namespace = config.namespace
}
Printf(ColorYellow, "Waiting for job %q from namespace %q\n", jobName, namespace)
clientset, err := loadKubernetesClient(config)
if err != nil {
ErrPrintln(ColorRed, err)
os.Exit(1)
}
job, err := clientset.Batch().Jobs(namespace).Get(jobName, apiv1.GetOptions{})
if err != nil {
ErrPrintln(ColorRed, err)
os.Exit(1)
}
checkJobStatus(job)
watcher, err := clientset.Batch().Jobs(namespace).Watch(apiv1.ListOptions{
FieldSelector: "metadata.name=" + jobName,
})
if err != nil {
ErrPrintln(ColorRed, err)
os.Exit(1)
}
timer := time.NewTimer(config.timeout)
poller := time.NewTicker(time.Minute)
pollErrorCount := 0
for {
var job *v1batch.Job
select {
case event := <-watcher.ResultChan():
var ok bool
job, ok = event.Object.(*v1batch.Job)
if !ok {
ErrPrintln(ColorRed, "Cannot decode job")
os.Exit(1)
}
if event.Type == watch.Deleted {
ErrPrintln(ColorRed, "Job was deleted")
os.Exit(1)
}
case <-timer.C:
ErrPrintln(ColorRed, "Timeout while waiting for job events")
os.Exit(1)
case <-poller.C:
job, err = clientset.Batch().Jobs(namespace).Get(jobName, apiv1.GetOptions{})
if err != nil {
pollErrorCount++
if pollErrorCount < 5 {
continue
}
ErrPrintln(ColorRed, err)
os.Exit(1)
}
}
checkJobStatus(job)
}
}
func checkJobStatus(job *v1batch.Job) {
if len(job.Status.Conditions) > 0 {
if job.Status.Conditions[0].Type == v1batch.JobComplete {
Println(ColorGreen, "Job completed")
os.Exit(0)
} else {
ErrPrintf(ColorRed, "Job failed: %s\n", job.Status.Conditions[0].Message)
os.Exit(1)
}
}
}