-
Notifications
You must be signed in to change notification settings - Fork 38
/
informer.go
106 lines (94 loc) · 2.32 KB
/
informer.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
104
105
106
package informer
import (
"github.com/kubespace/kubespace/pkg/informer/listwatcher"
"github.com/kubespace/kubespace/pkg/utils"
"k8s.io/klog/v2"
"sync"
"time"
)
// Handler informer监听到资源后,首先调用该处理器中的Check,判断是否需要处理
// 之后调用Handle进行处理
type Handler interface {
Check(interface{}) bool
Handle(interface{}) error
}
// ResourceHandler 通用资源处理对象,也可以自定义对象,实现Handler接口
type ResourceHandler struct {
CheckFunc func(interface{}) bool
HandleFunc func(interface{}) error
}
func (h *ResourceHandler) Check(obj interface{}) bool {
if h.CheckFunc != nil {
return h.CheckFunc(obj)
}
return true
}
func (h *ResourceHandler) Handle(obj interface{}) error {
return h.HandleFunc(obj)
}
type Informer interface {
Run(stopCh <-chan struct{})
AddHandler(Handler)
}
type informer struct {
listWatcher listwatcher.Interface
handlers []Handler
mu sync.Mutex
}
func NewInformer(listWatcher listwatcher.Interface) Informer {
return &informer{
listWatcher: listWatcher,
mu: sync.Mutex{},
}
}
func (b *informer) Run(stopCh <-chan struct{}) {
for {
if err := b.run(stopCh); err != nil {
klog.Errorf("run informer error: %s", err.Error())
// 5s后重试
tick := time.NewTicker(5 * time.Second)
select {
case <-tick.C:
continue
case <-stopCh:
break
}
}
break
}
}
func (b *informer) run(stopCh <-chan struct{}) error {
b.listWatcher.Run()
defer b.listWatcher.Stop()
for {
select {
case obj := <-b.listWatcher.Result():
go b.handle(obj)
case watchErr := <-b.listWatcher.WatchErr():
klog.Errorf("informer watch error: %v", watchErr)
case <-stopCh:
return nil
}
}
}
func (b *informer) AddHandler(handler Handler) {
b.mu.Lock()
b.handlers = append(b.handlers, handler)
b.mu.Unlock()
}
func (b *informer) handle(obj interface{}) {
for _, handler := range b.handlers {
if !handler.Check(obj) {
continue
}
// 开启一个goroutinue处理,不阻塞后续handler
go func(handler Handler) {
defer utils.HandleCrash(func(r interface{}) {
klog.Errorf("handle object crashed: %v", obj)
})
if err := handler.Handle(obj); err != nil {
klog.Errorf("informer key=%s, handle object error=%s, object=%+v", b.listWatcher.Key(), err.Error(), obj)
}
}(handler)
}
}