-
Notifications
You must be signed in to change notification settings - Fork 5
/
client_example_test.go
381 lines (311 loc) · 8.82 KB
/
client_example_test.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
package client_test
import (
"context"
"fmt"
"sort"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
klog "k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/stolostron/kubernetes-dependency-watches/client"
)
type reconciler struct{}
func (r *reconciler) Reconcile(_ context.Context, watcher client.ObjectIdentifier) (reconcile.Result, error) {
//nolint: forbidigo
fmt.Printf("An object that this object (%s) was watching was updated\n", watcher)
return reconcile.Result{}, nil
}
type ctrlRuntimeReconciler struct{}
func (r *ctrlRuntimeReconciler) Reconcile(_ context.Context, req reconcile.Request) (reconcile.Result, error) {
//nolint: forbidigo
fmt.Printf("The following reconcile request was received: %v\n", req)
return reconcile.Result{}, nil
}
func ExampleDynamicWatcher() {
// Start a test Kubernetes API.
testEnv := envtest.Environment{}
k8sConfig, err := testEnv.Start()
if err != nil {
panic(err)
}
defer func() {
err := testEnv.Stop()
if err != nil {
klog.Errorf("failed to stop the test Kubernetes API, error: %v", err)
}
}()
// Create the dynamic watcher.
dynamicWatcher, err := client.New(k8sConfig, &reconciler{}, nil)
if err != nil {
panic(err)
}
// A context that is canceled after a SIGINT signal is received.
parentCtx := ctrl.SetupSignalHandler()
// Create a child context that can be explicitly canceled.
ctx, cancel := context.WithCancel(parentCtx)
// Start the dynamic watcher in a separate goroutine to not block the main goroutine.
go func() {
err := dynamicWatcher.Start(ctx)
if err != nil {
panic(err)
}
}()
// Wait until the dynamic watcher has started.
<-dynamicWatcher.Started()
// Simulate something canceling the context in 5 seconds so that the example exits.
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
watcher := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "ConfigMap",
Namespace: "default",
Name: "watcher",
}
watched1 := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "Secret",
Namespace: "default",
Name: "watched1",
}
watched2 := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "Secret",
Namespace: "default",
Name: "watched2",
}
// Get notified about watcher when watched1 or watched2 is updated.
err = dynamicWatcher.AddOrUpdateWatcher(watcher, watched1, watched2)
if err != nil {
panic(err)
}
// Run until the context is canceled.
<-ctx.Done()
// Output:
}
func ExampleNewControllerRuntimeSource() {
// Start a test Kubernetes API.
testEnv := envtest.Environment{}
k8sConfig, err := testEnv.Start()
if err != nil {
panic(err)
}
defer func() {
err := testEnv.Stop()
if err != nil {
klog.Errorf("failed to stop the test Kubernetes API, error: %v", err)
}
}()
// Create a context that can be explicitly canceled.
ctx, cancel := context.WithCancel(context.TODO())
dynamicWatcherReconciler, sourceChan := client.NewControllerRuntimeSource()
// Create the dynamic watcher using the generated reconciler.
dynamicWatcher, err := client.New(k8sConfig, dynamicWatcherReconciler, nil)
if err != nil {
panic(err)
}
// Start the dynamic watcher in a separate goroutine to not block the main goroutine.
go func() {
err := dynamicWatcher.Start(ctx)
if err != nil {
panic(err)
}
}()
// Wait until the dynamic watcher has started.
<-dynamicWatcher.Started()
watcher := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "ConfigMap",
Namespace: "default",
Name: "watcher",
}
watched1 := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "Secret",
Namespace: "default",
Name: "watched1",
}
// Trigger the controller-runtime Reconcile method about watcher when watched1 is updated.
err = dynamicWatcher.AddOrUpdateWatcher(watcher, watched1)
if err != nil {
panic(err)
}
// Create a controller-runtime manager and register a simple controller.
options := ctrl.Options{
Cache: cache.Options{
DefaultNamespaces: map[string]cache.Config{
"default": {},
},
},
Scheme: scheme.Scheme,
Metrics: server.Options{
BindAddress: "0",
},
HealthProbeBindAddress: "0",
LeaderElection: false,
}
mgr, err := ctrl.NewManager(k8sConfig, options)
if err != nil {
panic(err)
}
// This controller watches ConfigMaps and will additionally reconcile any time the dynamic watcher sees a watched
// object is updated.
err = ctrl.NewControllerManagedBy(mgr).
Named("ExampleNewControllerRuntimeSource").
For(&corev1.ConfigMap{}).
WatchesRawSource(sourceChan).
Complete(&ctrlRuntimeReconciler{})
if err != nil {
panic(err)
}
// Simulate something canceling the context in 5 seconds so that the example exits.
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
err = mgr.Start(ctx)
if err != nil {
panic(err)
}
// Output:
}
func ExampleDynamicWatcher_Get() { //nolint: nosnakecase
// Start a test Kubernetes API.
testEnv := envtest.Environment{}
k8sConfig, err := testEnv.Start()
if err != nil {
panic(err)
}
// Create two test secrets to watch and cache
k8sClient, err := kubernetes.NewForConfig(k8sConfig)
if err != nil {
panic(err)
}
namespace := corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "example",
},
}
_, err = k8sClient.CoreV1().Namespaces().Create(context.TODO(), &namespace, metav1.CreateOptions{})
if err != nil {
panic(err)
}
secret1 := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "watched1",
Namespace: "example",
},
}
_, err = k8sClient.CoreV1().Secrets("example").Create(context.TODO(), &secret1, metav1.CreateOptions{})
if err != nil {
panic(err)
}
secret2 := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "watched2",
Namespace: "example",
},
}
_, err = k8sClient.CoreV1().Secrets("example").Create(context.TODO(), &secret2, metav1.CreateOptions{})
if err != nil {
panic(err)
}
defer func() {
err := testEnv.Stop()
if err != nil {
klog.Errorf("failed to stop the test Kubernetes API, error: %v", err)
}
}()
// Create the dynamic watcher with the cache enabled.
dynamicWatcher, err := client.New(
k8sConfig, &reconciler{}, &client.Options{DisableInitialReconcile: true, EnableCache: true},
)
if err != nil {
panic(err)
}
// Create a child context that can be explicitly canceled.
ctx, cancel := context.WithCancel(context.Background())
// Start the dynamic watcher in a separate goroutine to not block the main goroutine.
go func() {
err := dynamicWatcher.Start(ctx)
if err != nil {
panic(err)
}
}()
// Wait until the dynamic watcher has started.
<-dynamicWatcher.Started()
// Simulate something canceling the context in 5 seconds so that the example exits.
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
watcher := client.ObjectIdentifier{
Group: "",
Version: "v1",
Kind: "ConfigMap",
Namespace: "example",
Name: "watcher",
}
// Starting a query batch associates the get queries below as watched objects of this watcher.
err = dynamicWatcher.StartQueryBatch(watcher)
if err != nil {
panic(err)
}
gvk := schema.GroupVersionKind{Version: "v1", Kind: "Secret"}
// This creates a watch on watched1 and caches the object.
cachedSecret1, err := dynamicWatcher.Get(watcher, gvk, "example", "watched1")
if err != nil {
panic(err)
}
fmt.Println(cachedSecret1.GetName())
// This creates a watch on watched1 and caches the object.
cachedSecret2, err := dynamicWatcher.Get(watcher, gvk, "example", "watched2")
if err != nil {
panic(err)
}
fmt.Println(cachedSecret2.GetName())
// Ending a query batch will clean up any previous watches not referenced in the batch. In this case, there were
// none.
err = dynamicWatcher.EndQueryBatch(watcher)
if err != nil {
panic(err)
}
// Retrieve directly from the cache
cachedSecret1, err = dynamicWatcher.GetFromCache(gvk, "example", "watched1")
if err != nil {
panic(err)
}
fmt.Println(cachedSecret1.GetName())
// Retrieve watched objects from the cache for the watcher
cachedSecrets, err := dynamicWatcher.ListWatchedFromCache(watcher)
if err != nil {
panic(err)
}
// Sort the slice so the output is consistent for the output validation
sort.Slice(cachedSecrets, func(i, j int) bool { return cachedSecrets[i].GetName() < cachedSecrets[j].GetName() })
for _, cachedSecret := range cachedSecrets {
fmt.Println(cachedSecret.GetName())
}
// Run until the context is canceled.
<-ctx.Done()
// Output:
// watched1
// watched2
// watched1
// watched1
// watched2
}