-
Notifications
You must be signed in to change notification settings - Fork 687
/
watcher.go
301 lines (267 loc) · 7.12 KB
/
watcher.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package k8s
import (
"fmt"
"strings"
"sync"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
pwatch "k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/tools/cache"
)
type listWatchAdapter struct {
resource dynamic.ResourceInterface
fieldSelector string
labelSelector string
}
func (lw listWatchAdapter) List(options v1.ListOptions) (runtime.Object, error) {
options.FieldSelector = lw.fieldSelector
options.LabelSelector = lw.labelSelector
// silently coerce the returned *unstructured.UnstructuredList
// struct to a runtime.Object interface.
return lw.resource.List(options)
}
func (lw listWatchAdapter) Watch(options v1.ListOptions) (pwatch.Interface, error) {
options.FieldSelector = lw.fieldSelector
options.LabelSelector = lw.labelSelector
return lw.resource.Watch(options)
}
// Watcher is a kubernetes watcher that can watch multiple queries simultaneously
type Watcher struct {
Client *Client
watches map[ResourceType]watch
stop chan struct{}
wg sync.WaitGroup
mutex sync.Mutex
stopMu sync.Mutex
started bool
stopped bool
}
type watch struct {
query Query
resource dynamic.NamespaceableResourceInterface
store cache.Store
invoke func()
runner func()
}
// MustNewWatcher returns a Kubernetes watcher for the specified
// cluster or panics.
func MustNewWatcher(info *KubeInfo) *Watcher {
w, err := NewWatcher(info)
if err != nil {
panic(err)
}
return w
}
// NewWatcher returns a Kubernetes watcher for the specified cluster.
func NewWatcher(info *KubeInfo) (*Watcher, error) {
cli, err := NewClient(info)
if err != nil {
return nil, err
}
return cli.Watcher(), nil
}
// Watcher returns a Kubernetes Watcher for the specified client.
func (c *Client) Watcher() *Watcher {
w := &Watcher{
Client: c,
watches: make(map[ResourceType]watch),
stop: make(chan struct{}),
}
return w
}
// WatchQuery watches the set of resources identified by the supplied
// query and invokes the supplied listener whenever they change.
func (w *Watcher) WatchQuery(query Query, listener func(*Watcher)) error {
err := query.resolve(w.Client)
if err != nil {
return err
}
ri := query.resourceType
dyn, err := dynamic.NewForConfig(w.Client.config)
if err != nil {
return err
}
resource := dyn.Resource(schema.GroupVersionResource{
Group: ri.Group,
Version: ri.Version,
Resource: ri.Name,
})
var watched dynamic.ResourceInterface
if ri.Namespaced && query.Namespace != "" {
watched = resource.Namespace(query.Namespace)
} else {
watched = resource
}
invoke := func() {
w.mutex.Lock()
defer w.mutex.Unlock()
listener(w)
}
store, controller := cache.NewInformer(
listWatchAdapter{watched, query.FieldSelector, query.LabelSelector},
nil,
5*time.Minute,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
invoke()
},
UpdateFunc: func(oldObj, newObj interface{}) {
oldUn := oldObj.(*unstructured.Unstructured)
newUn := newObj.(*unstructured.Unstructured)
// we ignore updates for objects
// already in our store because we
// assume this means we made the
// change to them
if oldUn.GetResourceVersion() != newUn.GetResourceVersion() {
// kube-scheduler and kube-controller-manager endpoints are
// updated almost every second, leading to terrible noise,
// and hence constant listener invokation. So, here we
// ignore endpoint updates from kube-system namespace. More:
// https://github.com/kubernetes/kubernetes/issues/41635
// https://github.com/kubernetes/kubernetes/issues/34627
if oldUn.GetKind() == "Endpoints" &&
newUn.GetKind() == "Endpoints" &&
oldUn.GetNamespace() == "kube-system" &&
newUn.GetNamespace() == "kube-system" {
return
}
invoke()
}
},
DeleteFunc: func(obj interface{}) {
invoke()
},
},
)
runner := func() {
controller.Run(w.stop)
w.wg.Done()
}
w.watches[ri] = watch{
query: query,
resource: resource,
store: store,
invoke: invoke,
runner: runner,
}
return nil
}
// Start starts the watcher
func (w *Watcher) Start() {
w.mutex.Lock()
if w.started {
w.mutex.Unlock()
return
} else {
w.started = true
w.mutex.Unlock()
}
for kind := range w.watches {
w.sync(kind)
}
for _, watch := range w.watches {
watch.invoke()
}
w.wg.Add(len(w.watches))
for _, watch := range w.watches {
go watch.runner()
}
}
func (w *Watcher) sync(kind ResourceType) {
watch := w.watches[kind]
resources, err := w.Client.ListQuery(watch.query)
if err != nil {
panic(err)
}
for _, rsrc := range resources {
var uns unstructured.Unstructured
uns.SetUnstructuredContent(rsrc)
err = watch.store.Update(&uns)
if err != nil {
panic(err)
}
}
}
// List lists all the resources with kind `kind`
func (w *Watcher) List(kind string) []Resource {
ri, err := w.Client.ResolveResourceType(kind)
if err != nil {
panic(err)
}
watch, ok := w.watches[ri]
if ok {
objs := watch.store.List()
result := make([]Resource, len(objs))
for idx, obj := range objs {
result[idx] = obj.(*unstructured.Unstructured).UnstructuredContent()
}
return result
} else {
return nil
}
}
// UpdateStatus updates the status of the `resource` provided
func (w *Watcher) UpdateStatus(resource Resource) (Resource, error) {
ri, err := w.Client.ResolveResourceType(resource.QKind())
if err != nil {
return nil, err
}
watch, ok := w.watches[ri]
if !ok {
return nil, fmt.Errorf("no watch: %v, %v", ri, w.watches)
}
var uns unstructured.Unstructured
uns.SetUnstructuredContent(resource)
var cli dynamic.ResourceInterface
if ri.Namespaced {
cli = watch.resource.Namespace(uns.GetNamespace())
} else {
cli = watch.resource
}
result, err := cli.UpdateStatus(&uns, v1.UpdateOptions{})
if err != nil {
return nil, err
} else {
watch.store.Update(result)
return result.UnstructuredContent(), nil
}
}
// Get gets the `qname` resource (of kind `kind`)
func (w *Watcher) Get(kind, qname string) Resource {
resources := w.List(kind)
for _, res := range resources {
if strings.EqualFold(res.QName(), qname) {
return res
}
}
return Resource{}
}
// Exists returns true if the `qname` resource (of kind `kind`) exists
func (w *Watcher) Exists(kind, qname string) bool {
return w.Get(kind, qname).Name() != ""
}
// Stop stops a watch. It is safe to call Stop from multiple
// goroutines and call it multiple times. This is useful, e.g. for
// implementing a timed wait pattern. You can have your watch callback
// test for a condition and invoke Stop() when that condition is met,
// while simultaneously havin a background goroutine call Stop() when
// a timeout is exceeded and not worry about these two things racing
// each other (at least with respect to invoking Stop()).
func (w *Watcher) Stop() {
// Use a separate lock for Stop so it is safe to call from a watch callback.
w.stopMu.Lock()
defer w.stopMu.Unlock()
if !w.stopped {
close(w.stop)
w.stopped = true
}
}
func (w *Watcher) Wait() {
w.Start()
w.wg.Wait()
}