-
Notifications
You must be signed in to change notification settings - Fork 14
/
watch.go
80 lines (68 loc) · 1.71 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
package main
import (
"context"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/watch"
)
type Target struct {
Namespace string
Pod string
Container string
}
// NewTarget creates new Target object
func NewTarget(namespace, pod, container string) *Target {
return &Target{
Namespace: namespace,
Pod: pod,
Container: container,
}
}
// GetID returns target ID
func (t *Target) GetID() string {
return t.Namespace + "_" + t.Pod + "_" + t.Container
}
// Watch starts and listens Kubernetes Pod events
func Watch(ctx context.Context, watcher watch.Interface) (chan *Target, chan *Target, chan *Target) {
added := make(chan *Target)
finished := make(chan *Target)
deleted := make(chan *Target)
go func() {
for {
select {
case e := <-watcher.ResultChan():
if e.Object == nil {
return
}
pod := e.Object.(*v1.Pod)
switch e.Type {
case watch.Added:
if pod.Status.Phase != v1.PodRunning {
continue
}
for _, container := range pod.Spec.Containers {
added <- NewTarget(pod.Namespace, pod.Name, container.Name)
}
case watch.Modified:
switch pod.Status.Phase {
case v1.PodRunning:
for _, container := range pod.Spec.Containers {
added <- NewTarget(pod.Namespace, pod.Name, container.Name)
}
case v1.PodSucceeded, v1.PodFailed:
for _, container := range pod.Spec.Containers {
finished <- NewTarget(pod.Namespace, pod.Name, container.Name)
}
}
case watch.Deleted:
for _, container := range pod.Spec.Containers {
deleted <- NewTarget(pod.Namespace, pod.Name, container.Name)
}
}
case <-ctx.Done():
watcher.Stop()
return
}
}
}()
return added, finished, deleted
}