/
watcher.go
411 lines (355 loc) · 7.52 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package k8s
import (
"bufio"
"container/heap"
"context"
"encoding/json"
"io"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/mitchellh/mapstructure"
)
type itemObj interface {
ResourceVersion() string
Name() string
}
type listResponse struct {
Items []interface{}
Metadata struct {
Continue string
ResourceVersion string
}
}
type pagerClient interface {
Get(path string) (*listResponse, error)
}
type pager struct {
path string
client pagerClient
limit int
// results
items []interface{}
resourceVersion string
}
func (p *pager) run(stopCh chan struct{}) error {
resourceVersion := p.resourceVersion
limit := p.limit
if limit == 0 {
limit = 20
}
cont := ""
for {
path := p.path
if !strings.Contains(path, "?") {
path = path + "?"
} else {
path = path + "&"
}
if resourceVersion != "" && cont == "" {
// continue and resourceVersion cannot be set at the same time
path += "resourceVersion=" + resourceVersion + "&"
}
if cont != "" {
path += "continue=" + cont + "&"
}
if limit != 0 {
path += "limit=" + strconv.Itoa(limit)
}
result, err := p.client.Get(path)
if err != nil {
return err
}
p.items = append(p.items, result.Items...)
if result.Metadata.Continue == "" {
resourceVersion = result.Metadata.ResourceVersion
break
}
cont = result.Metadata.Continue
}
p.resourceVersion = resourceVersion
return nil
}
type WatchEntry struct {
item itemObj
typ string
// internal fields for the sort heap
index int
timestamp time.Time
}
type Watcher struct {
logger hclog.Logger
client *KubeClient
stopCh chan struct{}
store *store
path string
list bool
limit int
obj itemObj
latestResourceVersion string
}
func NewWatcher(logger hclog.Logger, client *KubeClient, path string, obj itemObj) (*Watcher, error) {
w := &Watcher{
logger: logger,
client: client,
store: newStore(),
obj: obj,
path: path,
}
// validate that we can get the items
if _, err := w.client.GetFull(path, nil); err != nil {
return nil, err
}
// validate that we can watch the items
if _, err := w.client.Watch(path); err != nil {
return nil, err
}
return w, nil
}
func (w *Watcher) decodeObj(item interface{}) (itemObj, error) {
obj := reflect.New(reflect.TypeOf(w.obj).Elem()).Interface()
if err := mapstructure.Decode(item, obj); err != nil {
return nil, err
}
return obj.(itemObj), nil
}
func (w *Watcher) IsClosed() bool {
select {
case <-w.stopCh:
return true
default:
return false
}
}
func (w *Watcher) watchImpl(resourceVersion string, handler func(typ string, item itemObj) error) error {
path := w.path + "?watch=true"
if resourceVersion != "" {
path += "&resourceVersion=" + resourceVersion
}
resp, err := w.client.Watch(path)
if err != nil {
return err
}
buffer := bufio.NewReader(resp.Body)
for {
res, err := buffer.ReadBytes(byte('\n'))
if err != nil {
if err == io.EOF {
continue
}
return err
}
if err := isError(res); err != nil {
return err
}
if w.IsClosed() {
return nil
}
var evnt WatchEvent
if err := json.Unmarshal(res, &evnt); err != nil {
w.logger.Error("failed to decode watch event", "err", err)
continue
}
obj, err := w.decodeObj(evnt.Object)
if err != nil {
w.logger.Error("failed to decode custom event", "err", err)
continue
}
if err := handler(evnt.Type, obj); err != nil {
return err
}
}
}
func (w *Watcher) Get(path string) (*listResponse, error) {
data, err := w.client.GetFull(path, nil)
if err != nil {
return nil, err
}
result := &listResponse{}
if err := json.Unmarshal(data, &result); err != nil {
return nil, err
}
return result, nil
}
func (w *Watcher) WithLimit(l int) *Watcher {
w.limit = l
return w
}
func (w *Watcher) WithList(list bool) *Watcher {
w.list = list
return w
}
func (w *Watcher) Run(stopCh chan struct{}) {
w.stopCh = stopCh
go w.runWithBackoff()
}
func (w *Watcher) runWithBackoff() {
for {
err := w.runImpl()
if err != nil {
w.logger.Error("failed to watch", "err", err)
}
// TODO: Use exponential backoff
select {
case <-time.After(2 * time.Second):
case <-w.stopCh:
return
}
}
}
func (w *Watcher) listImpl(resourceVersion string) (*pager, error) {
pager := &pager{
path: w.path,
client: w,
limit: w.limit,
resourceVersion: resourceVersion,
}
err := pager.run(w.stopCh)
return pager, err
}
func isExpired(err error) bool {
return err == errExpired
}
func (w *Watcher) runImpl() error {
resourceVersion := w.latestResourceVersion
if resourceVersion == "" {
// start from the beginning
resourceVersion = "0"
}
defer func() {
w.latestResourceVersion = resourceVersion
}()
// try to list first with the latest known resourceversion
pager, err := w.listImpl(resourceVersion)
if err != nil {
if isExpired(err) {
// the resource version is not available, retry againg
// but this time from the latest known value
pager, err = w.listImpl("")
}
}
if err != nil {
return err
}
// decode and insert all the objects
if w.list {
objs := []itemObj{}
for _, i := range pager.items {
item, err := w.decodeObj(i)
if err != nil {
return err
}
objs = append(objs, item)
}
for _, obj := range objs {
w.store.add("", obj)
}
}
resourceVersion = pager.resourceVersion
// watch
err = w.watchImpl(resourceVersion, func(typ string, item itemObj) error {
w.store.add(typ, item)
resourceVersion = item.ResourceVersion()
return nil
})
return err
}
func (w *Watcher) ForEach(handler func(task *WatchEntry, i interface{})) {
ctx, cancelFn := context.WithCancel(context.Background())
go func() {
<-w.stopCh
cancelFn()
}()
go func() {
for {
task := w.store.pop(ctx)
if ctx.Err() != nil {
return
}
handler(task, task.item)
}
}()
}
type store struct {
heapImpl storeHeapImpl
lock sync.Mutex
items map[string]*WatchEntry
updateCh chan struct{}
}
func newStore() *store {
return &store{
heapImpl: storeHeapImpl{},
items: map[string]*WatchEntry{},
updateCh: make(chan struct{}),
}
}
func (s *store) add(typ string, i itemObj) {
id := i.Name()
s.lock.Lock()
defer s.lock.Unlock()
if ii, ok := s.items[id]; ok {
// replace
ii.item = i
ii.timestamp = time.Now()
heap.Fix(&s.heapImpl, ii.index)
} else {
// push
tt := &WatchEntry{
item: i,
typ: typ,
timestamp: time.Now(),
}
s.items[id] = tt
heap.Push(&s.heapImpl, tt)
}
select {
case s.updateCh <- struct{}{}:
default:
}
}
func (s *store) pop(ctx context.Context) *WatchEntry {
POP:
s.lock.Lock()
if len(s.heapImpl) != 0 {
// pop the first value
tt := heap.Pop(&s.heapImpl).(*WatchEntry)
delete(s.items, tt.item.Name())
s.lock.Unlock()
return tt
}
s.lock.Unlock()
select {
case <-s.updateCh:
goto POP
case <-ctx.Done():
return nil
}
}
type storeHeapImpl []*WatchEntry
func (t storeHeapImpl) Len() int { return len(t) }
func (t storeHeapImpl) Less(i, j int) bool {
return t[i].item.ResourceVersion() < t[j].item.ResourceVersion()
}
func (t storeHeapImpl) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
t[i].index = i
t[j].index = j
}
func (t *storeHeapImpl) Push(x interface{}) {
n := len(*t)
item := x.(*WatchEntry)
item.index = n
*t = append(*t, item)
}
func (t *storeHeapImpl) Pop() interface{} {
old := *t
n := len(old)
item := old[n-1]
old[n-1] = nil
item.index = -1
*t = old[0 : n-1]
return item
}