/
watch.go
103 lines (92 loc) · 2.22 KB
/
watch.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
package core
import (
"fmt"
"github.com/viant/endly"
"k8s.io/api/apps/v1"
"k8s.io/api/apps/v1beta2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/watch"
"time"
)
const maxStatusWaitTimeInSec = 30
func getWatcher(context *endly.Context, watchRequest interface{}) (watch.Interface, error) {
if watchRequest == nil {
return nil, nil
}
var watchResponse interface{}
if err := endly.RunWithoutLogging(context, watchRequest, &watchResponse); err != nil {
return nil, err
}
if result, ok := watchResponse.(watch.Interface); ok {
return result, nil
}
return nil, fmt.Errorf("unsupported type: %T\n", watchResponse)
}
func waitForEvent(watcher watch.Interface) (*watch.Event, error) {
if watcher == nil {
return nil, nil
}
defer watcher.Stop()
channel := watcher.ResultChan()
select {
case event := <-channel:
return &event, nil
case <-time.After(maxStatusWaitTimeInSec * time.Second):
break
}
return nil, nil
}
func waitUntilReady(watcher watch.Interface) error {
if watcher == nil {
return nil
}
defer watcher.Stop()
channel := watcher.ResultChan()
for {
select {
case event := <-channel:
switch event.Type {
case watch.Added, watch.Modified:
switch res := event.Object.(type) {
case *v1.Deployment:
if isDeploymentReady(res) {
return nil
}
case *corev1.ReplicationController:
if isReplicationControllerReady(res) {
return nil
}
case *corev1.Pod:
if isPodReady(res) {
return nil
}
case *v1beta2.Deployment:
if isV1beta2DeploymentReady(res) {
return nil
}
default:
return nil
}
}
case <-time.After(maxStatusWaitTimeInSec * time.Second):
return nil
}
}
}
func isPodReady(resource *corev1.Pod) bool {
for _, cond := range resource.Status.Conditions {
if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {
return true
}
}
return false
}
func isDeploymentReady(resource *v1.Deployment) bool {
return resource.Status.ReadyReplicas > 0
}
func isV1beta2DeploymentReady(resource *v1beta2.Deployment) bool {
return resource.Status.ReadyReplicas > 0
}
func isReplicationControllerReady(resource *corev1.ReplicationController) bool {
return resource.Status.ReadyReplicas > 0
}