/
watcher.go
230 lines (207 loc) · 6.37 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
package watcher
import (
"context"
"fmt"
"log"
"strconv"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
)
type resourceVersionGetter interface {
GetResourceVersion() string
}
type WatchNotifyFunctions struct {
AddFunc func(obj *unstructured.Unstructured)
UpdateFunc func(obj *unstructured.Unstructured)
DeleteFunc func(obj *unstructured.Unstructured)
OnError func(err error)
}
type WatcherInterface interface {
Start(notifyF WatchNotifyFunctions, gvr schema.GroupVersionResource, listOptions metav1.ListOptions) error
Stop()
Destroy()
}
type Watcher struct {
preList bool
client dynamic.Interface
watcher watch.Interface
lastResourceVersion string
running bool
}
func NewWatcher(k8sClient dynamic.Interface, preList bool) WatcherInterface {
return &Watcher{client: k8sClient, watcher: nil, running: false, preList: preList, lastResourceVersion: ""}
}
func (w *Watcher) Start(notifyF WatchNotifyFunctions, gvr schema.GroupVersionResource, listOptions metav1.ListOptions) error {
if w.watcher != nil {
return fmt.Errorf("watcher already started")
}
// Get a list of current namespaces from the API server
nameSpaceGvr := schema.GroupVersionResource{
Group: "", // The group is empty for core API groups
Version: "v1",
Resource: "namespaces",
}
// List the namespaces
namespaces, err := w.client.Resource(nameSpaceGvr).List(context.Background(), metav1.ListOptions{})
if err != nil {
return err
}
// List of current objects
w.lastResourceVersion = ""
if w.preList {
listOptions.Watch = false
for _, ns := range namespaces.Items {
list, err := w.client.Resource(gvr).Namespace(ns.GetName()).List(context.Background(), listOptions)
if err != nil {
return err
}
for i, item := range list.Items {
if isResourceVersionHigher(item.GetResourceVersion(), w.lastResourceVersion) {
// Update the resourceVersion to the latest
w.lastResourceVersion = item.GetResourceVersion()
if w.preList {
notifyF.AddFunc(&item)
}
// Make sure the item is scraped by the GC
list.Items[i] = unstructured.Unstructured{}
}
}
list.Items = nil
list = nil
}
}
// Start the watcher
listOptions.ResourceVersion = w.lastResourceVersion
listOptions.Watch = true
listOptions.AllowWatchBookmarks = true
w.watcher, err = w.client.Resource(gvr).Namespace("").Watch(context.TODO(), listOptions)
if err != nil {
return err
}
w.running = true
go func() {
// Watch for events
for {
if w.watcher == nil {
w.watcher, err = w.client.Resource(gvr).Namespace("").Watch(context.TODO(), listOptions)
if err != nil {
if notifyF.OnError != nil {
notifyF.OnError(err)
} else {
log.Printf("watcher error: %v", err)
}
return
}
}
event, ok := <-w.watcher.ResultChan()
if !ok {
if w.running {
log.Printf("Restarting watcher on object %+v", gvr)
w.watcher.Stop()
w.watcher = nil
listOptions.ResourceVersion = w.lastResourceVersion
// Retry 5 times with exponential backoff.
for i := 0; i < 5; i++ {
w.watcher, err = w.client.Resource(gvr).Namespace("").Watch(context.TODO(), listOptions)
if err == nil {
break
}
log.Printf("watcher restart error: %v, on object: %+v, retrying...", err, gvr)
time.Sleep(time.Second * time.Duration(i*2)) // Exponential backoff
}
if err != nil {
// If the watcher restart fails after 5 attempts, log the error and call the OnError function.
if notifyF.OnError != nil {
notifyF.OnError(err)
} else {
log.Printf("Final watcher restart error: %v, on object: %+v", err, gvr)
log.Println("Closing watcher")
}
return
}
continue
} else {
// Stop the watcher
return
}
}
if metaObject, ok := event.Object.(resourceVersionGetter); ok {
// Update the resourceVersion to the latest
if metaObject.GetResourceVersion() != "" && isResourceVersionHigher(metaObject.GetResourceVersion(), w.lastResourceVersion) {
w.lastResourceVersion = metaObject.GetResourceVersion()
}
}
switch event.Type {
case watch.Added:
// Convert the object to unstructured
addedObject := event.Object.(*unstructured.Unstructured)
if addedObject == nil {
log.Printf("watcher error: addedObject is nil")
continue
}
notifyF.AddFunc(addedObject)
addedObject = nil // Make sure the item is scraped by the GC
case watch.Modified:
// Convert the object to unstructured
modifiedObject := event.Object.(*unstructured.Unstructured)
if modifiedObject == nil {
log.Printf("watcher error: modifiedObject is nil")
continue
}
notifyF.UpdateFunc(modifiedObject)
modifiedObject = nil // Make sure the item is scraped by the GC
case watch.Deleted:
// Convert the object to unstructured
deletedObject := event.Object.(*unstructured.Unstructured)
if deletedObject == nil {
log.Printf("watcher error: deletedObject is nil")
continue
}
notifyF.DeleteFunc(deletedObject)
deletedObject = nil // Make sure the item is scraped by the GC
case watch.Error:
// Convert the object to metav1.Status
watchError := event.Object.(*metav1.Status)
if watchError != nil {
if watchError.Code == 410 {
// If the resourceVersion is too old, reset the resourceVersion to the latest.
// https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions
w.lastResourceVersion = ""
}
}
continue
}
}
}()
return nil
}
func (w *Watcher) Stop() {
if w.watcher != nil {
w.running = false
w.watcher.Stop()
w.watcher = nil
}
}
func (w *Watcher) Destroy() {
}
func isResourceVersionHigher(resourceVersion string, currentResourceVersion string) bool {
// If the currentResourceVersion is empty, return true
if currentResourceVersion == "" {
return true
}
// Convert the resourceVersion to int64
resourceVersionInt, err := strconv.ParseInt(resourceVersion, 10, 64)
if err != nil {
return false
}
// Convert the currentResourceVersion to int64
currentResourceVersionInt, err := strconv.ParseInt(currentResourceVersion, 10, 64)
if err != nil {
return false
}
return resourceVersionInt > currentResourceVersionInt
}