/
watch.go
58 lines (51 loc) · 1.19 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
package informerwatch
import (
"sync"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
type InformerWatch struct {
informer cache.SharedInformer
onceStop sync.Once
stopChan chan struct{}
resultChan chan watch.Event
}
func NewInformerWatch(informer cache.SharedInformer) *InformerWatch {
iw := &InformerWatch{
informer: informer,
stopChan: make(chan struct{}),
resultChan: make(chan watch.Event),
}
iw.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
iw.resultChan <- watch.Event{
Type: watch.Added,
Object: obj.(runtime.Object),
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
iw.resultChan <- watch.Event{
Type: watch.Modified,
Object: newObj.(runtime.Object),
}
},
DeleteFunc: func(obj interface{}) {
iw.resultChan <- watch.Event{
Type: watch.Deleted,
Object: obj.(runtime.Object),
}
},
})
go iw.informer.Run(iw.stopChan)
return iw
}
func (iw *InformerWatch) ResultChan() <-chan watch.Event {
return iw.resultChan
}
func (iw *InformerWatch) Stop() {
iw.onceStop.Do(func() {
close(iw.stopChan)
close(iw.resultChan)
})
}