-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
221 lines (187 loc) · 5.69 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
/*
Copyright 2024 Nokia.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pkgserver
/*
import (
"context"
"fmt"
"reflect"
"sync"
"github.com/henderiw/logger/log"
pkgv1alpha1 "github.com/kform-dev/pkg-server/apis/pkg/v1alpha1"
watchermanager "github.com/kform-dev/pkg-server/pkg/watcher-manager"
"k8s.io/apimachinery/pkg/api/meta"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
)
// implements the watchermanager Watcher interface
// implenents the k8s watch.Interface interface
type watcher struct {
// interfce to the observer
cancel func()
resultChan chan watch.Event
watcherManager watchermanager.WatcherManager
// protection against concurrent access
m sync.Mutex
eventCallback func(eventType watch.EventType, obj runtime.Object) bool
done bool
}
var _ watch.Interface = &watcher{}
// Stop stops watching. Will close the channel returned by ResultChan(). Releases
// any resources used by the watch.
func (r *watcher) Stop() {
r.cancel()
}
// ResultChan returns a chan which will receive all the events. If an error occurs
// or Stop() is called, the implementation will close this channel and
// release any resources used by the watch.
func (r *watcher) ResultChan() <-chan watch.Event {
return r.resultChan
}
// Implement the watcchermanafer.Watcher interface
// OnChange is the callback called when a object changes.
func (r *watcher) OnChange(eventType watch.EventType, obj runtime.Object) bool {
r.m.Lock()
defer r.m.Unlock()
return r.eventCallback(eventType, obj)
}
func (r *watcher) listAndWatch(ctx context.Context, l lister, options *metainternalversion.ListOptions) {
log := log.FromContext(ctx)
if err := r.innerListAndWatch(ctx, l, options); err != nil {
// TODO: We need to populate the object on this error
// Most likely happens when we cancel a context, stop a watch
log.Info("sending error to watch stream", "error", err)
ev := watch.Event{
Type: watch.Error,
Object: &pkgv1alpha1.PackageRevision{},
}
r.resultChan <- ev
}
r.cancel()
close(r.resultChan)
}
// innerListAndWatch provides the callback handler
// 1. add a callback handler to receive any event we get while collecting the list of existing resources
// 2.
func (r *watcher) innerListAndWatch(ctx context.Context, l lister, options *metainternalversion.ListOptions) error {
log := log.FromContext(ctx)
errorResult := make(chan error)
// backlog logs the events during startup
var backlog []watch.Event
// Make sure we hold the lock when setting the eventCallback, as it
// will be read by other goroutines when events happen.
r.m.Lock()
r.eventCallback = func(eventType watch.EventType, obj runtime.Object) bool {
if r.done {
return false
}
backlog = append(backlog, watch.Event{
Type: eventType,
Object: obj,
})
return true
}
r.m.Unlock()
// we add the watcher to the watchermanager and start building a backlog for intermediate changes
// while we startup, the backlog will be replayed once synced
log.Info("starting watch")
if err := r.watcherManager.Add(ctx, options, r); err != nil {
return err
}
// options.Watch means watch only no listing
if !options.Watch {
log.Info("starting list watch")
obj, err := l.list(ctx, options)
if err != nil {
r.setDone()
return err
}
cfgList, ok := obj.(*pkgv1alpha1.PackageRevisionList)
if !ok {
r.setDone()
return fmt.Errorf("expecting type, got: %s", reflect.TypeOf(obj).Name())
}
for _, obj := range cfgList.Items {
obj := obj
ev := watch.Event{
Type: watch.Added,
Object: &obj,
}
r.sendWatchEvent(ctx, ev)
}
log.Info("finished list watch")
} else {
log.Info("watch only, no list")
}
// Repeatedly flush the backlog until we catch up
for {
r.m.Lock()
chunk := backlog
backlog = nil
r.m.Unlock()
if len(chunk) == 0 {
break
}
log.Info("flushing backlog", "chunk length", len(chunk))
for _, ev := range chunk {
r.sendWatchEvent(ctx, ev)
}
}
r.m.Lock()
// Pick up anything that squeezed in
for _, ev := range backlog {
r.sendWatchEvent(ctx, ev)
}
log.Info("moving into streaming mode")
r.eventCallback = func(eventType watch.EventType, obj runtime.Object) bool {
accessor, _ := meta.Accessor(obj)
log.Info("eventCallBack", "eventType", eventType, "nsn", fmt.Sprintf("%s/%s", accessor.GetNamespace(), accessor.GetName()))
if r.done {
return false
}
ev := watch.Event{
Type: eventType,
Object: obj,
}
r.sendWatchEvent(ctx, ev)
return true
}
r.m.Unlock()
select {
case <-ctx.Done():
r.setDone()
return ctx.Err()
case err := <-errorResult:
r.setDone()
return err
}
}
func (r *watcher) sendWatchEvent(ctx context.Context, event watch.Event) {
// TODO: Handle the case that the watch channel is full?
if event.Object != nil {
accessor, _ := meta.Accessor(event.Object)
log := log.FromContext(ctx).With("event", event.Type, "nsn", fmt.Sprintf("%s/%s", accessor.GetNamespace(), accessor.GetName()))
log.Info("sending watch event")
} else {
log := log.FromContext(ctx).With("event", event.Type)
log.Info("sending watch event")
}
r.resultChan <- event
}
func (r *watcher) setDone() {
r.m.Lock()
defer r.m.Unlock()
r.done = true
}
*/