/
identified_resources_pods.go
86 lines (65 loc) · 1.83 KB
/
identified_resources_pods.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
package resources
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
)
func (r IdentifiedResources) PodResources(labelSelector labels.Selector) UniquePodWatcher {
return UniquePodWatcher{labelSelector, r.coreClient}
}
type PodWatcherI interface {
Watch(podsToWatchCh chan corev1.Pod, cancelCh chan struct{}) error
}
type UniquePodWatcher struct {
labelSelector labels.Selector
coreClient kubernetes.Interface
}
var _ PodWatcherI = UniquePodWatcher{}
func (w UniquePodWatcher) Watch(podsToWatchCh chan corev1.Pod, cancelCh chan struct{}) error {
nonUniquePodsToWatchCh := make(chan corev1.Pod)
go func() {
podWatcher := NewPodWatcher(
w.coreClient.CoreV1().Pods(""),
metav1.ListOptions{LabelSelector: w.labelSelector.String()},
)
err := podWatcher.Watch(nonUniquePodsToWatchCh, cancelCh)
if err != nil {
fmt.Printf("Pod watching error: %s\n", err) // TODO
}
close(nonUniquePodsToWatchCh)
}()
// Send unique pods to the watcher client
watchedPods := map[string]struct{}{}
for pod := range nonUniquePodsToWatchCh {
podUID := string(pod.UID)
if _, found := watchedPods[podUID]; found {
continue
}
watchedPods[podUID] = struct{}{}
podsToWatchCh <- pod
}
return nil
}
type FilteringPodWatcher struct {
MatcherFunc func(*corev1.Pod) bool
Watcher PodWatcherI
}
var _ PodWatcherI = FilteringPodWatcher{}
func (w FilteringPodWatcher) Watch(podsToWatchCh chan corev1.Pod, cancelCh chan struct{}) error {
filteredCh := make(chan corev1.Pod)
go func() {
err := w.Watcher.Watch(filteredCh, cancelCh)
if err != nil {
fmt.Printf("Pod watching error: %s\n", err) // TODO
}
close(filteredCh)
}()
for pod := range filteredCh {
if w.MatcherFunc(&pod) {
podsToWatchCh <- pod
}
}
return nil
}