/
main.go
381 lines (314 loc) · 10.7 KB
/
main.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 main
import (
"context"
"fmt"
"os"
"time"
scopecache "github.com/everettraven/telescopia/pkg/cache"
"github.com/everettraven/telescopia/pkg/cache/cluster"
"github.com/everettraven/telescopia/pkg/cache/components"
"github.com/everettraven/telescopia/pkg/cache/namespace"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
func main() {
namespacedCache()
// clusterCache()
// scopedCache()
}
func scopedCache() {
cfg := config.GetConfigOrDie()
cacheScheme := runtime.NewScheme()
err := corev1.AddToScheme(cacheScheme)
if err != nil {
fmt.Println("error adding to cache scheme:", err)
os.Exit(1)
}
scopeCacheBuild, err := scopecache.ScopedCacheBuilder()(cfg, cache.Options{Scheme: cacheScheme})
if err != nil {
fmt.Println("error building ScopedCache:", err)
os.Exit(3)
}
scopeCache := scopeCacheBuild.(*scopecache.ScopedCache)
cli, err := client.New(cfg, client.Options{})
if err != nil {
fmt.Println("error creating client: %w", err)
os.Exit(2)
}
createResources(cli)
// create an informer at the cluster level to look for ServiceAccounts
k8sClient := kubernetes.NewForConfigOrDie(cfg)
resync := 5 * time.Second
saGvk := corev1.SchemeGroupVersion.WithKind("ServiceAccount")
infFact := informers.NewSharedInformerFactoryWithOptions(k8sClient, resync)
saInf, err := infFact.ForResource(corev1.SchemeGroupVersion.WithResource("serviceaccounts"))
if err != nil {
fmt.Println("error in getting pod informer | error:", err)
}
scopeCache.AddInformer(components.InformerOptions{
Gvk: saGvk,
Key: "serviceaccount-informer",
Informer: saInf,
Dependent: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID("dependent-0"),
},
},
})
// create some informers for pods in specific namespaces
podGvk := corev1.SchemeGroupVersion.WithKind("Pod")
for i := 0; i < 3; i++ {
namespace := fmt.Sprintf("testns-%d", i)
infFact := informers.NewSharedInformerFactoryWithOptions(k8sClient, resync, informers.WithNamespace(namespace))
podInf, err := infFact.ForResource(corev1.SchemeGroupVersion.WithResource("pods"))
if err != nil {
fmt.Println("error in getting pod informer for ns", namespace, "| error:", err)
continue
}
scopeCache.AddInformer(components.InformerOptions{
Namespace: namespace,
Gvk: podGvk,
Key: "pod-informer",
Informer: podInf,
Dependent: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID(fmt.Sprintf("dependent-%d", i)),
},
},
})
}
scopeCache.Start(context.Background())
// give resources time to populate
time.Sleep(10 * time.Second)
fmt.Println("Get Pod `testns-0/testpod-0`")
fmt.Println("=================================")
// get a pod
pod := &corev1.Pod{}
err = scopeCache.Get(context.Background(), types.NamespacedName{Namespace: "testns-0", Name: "testpod-0"}, pod)
if err != nil {
fmt.Println("error getting pod from cache:", err)
}
fmt.Println("Pod:", pod)
fmt.Println("=================================")
fmt.Println("Pods in all watched namespaces:")
fmt.Println("=================================")
podList := &corev1.PodList{}
err = scopeCache.List(context.Background(), podList, &client.ListOptions{LabelSelector: labels.Everything()})
if err != nil {
fmt.Println("error listing pods:", err)
}
for _, podObj := range podList.Items {
fmt.Println("pod.Namespace:", podObj.Namespace, "pod.Name:", podObj.Name)
}
fmt.Println("=================================")
fmt.Println("Get ServiceAccount `default/default`")
fmt.Println("=================================")
sa := &corev1.ServiceAccount{}
err = scopeCache.Get(context.Background(), types.NamespacedName{Namespace: "default", Name: "default"}, sa)
if err != nil {
fmt.Println("error getting ServiceAccount:", err)
}
fmt.Println("ServiceAccount:", sa)
fmt.Println("=================================")
fmt.Println("ServiceAccounts across the cluster")
fmt.Println("=================================")
saList := &corev1.ServiceAccountList{}
err = scopeCache.List(context.Background(), saList, &client.ListOptions{LabelSelector: labels.Everything()})
if err != nil {
fmt.Println("error listing serviceaccounts:", err)
}
for _, saObj := range saList.Items {
fmt.Println("serviceaccount.Namespace:", saObj.Namespace, "serviceaccount.Name:", saObj.Name)
}
fmt.Println("=================================")
}
func clusterCache() {
cfg := config.GetConfigOrDie()
clusterCache := cluster.NewClusterScopedCache()
cli, err := client.New(cfg, client.Options{})
if err != nil {
fmt.Println("error creating client: %w", err)
os.Exit(2)
}
createResources(cli)
// create some informers
k8sClient := kubernetes.NewForConfigOrDie(cfg)
resync := 5 * time.Second
podGvk := corev1.SchemeGroupVersion.WithKind("Pod")
infFact := informers.NewSharedInformerFactoryWithOptions(k8sClient, resync)
podInf, err := infFact.ForResource(corev1.SchemeGroupVersion.WithResource("pods"))
if err != nil {
fmt.Println("error in getting pod informer | error:", err)
}
clusterCache.AddInformer(components.InformerOptions{
Gvk: podGvk,
Key: "pod-informer",
Informer: podInf,
Dependent: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID("dependent-0"),
},
},
})
// add the informer again with a different dependent
clusterCache.AddInformer(components.InformerOptions{
Gvk: podGvk,
Key: "pod-informer",
Informer: podInf,
Dependent: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID("dependent-1"),
},
},
})
fmt.Println("pod-informer dependents", len(clusterCache.GvkInformers[podGvk]["pod-informer"].GetDependents()))
clusterCache.Start()
// give resources time to populate
time.Sleep(10 * time.Second)
fmt.Println("Get Pod `testns-0/testpod-0`")
fmt.Println("=================================")
// get a pod
pod, err := clusterCache.Get(types.NamespacedName{Namespace: "testns-0", Name: "testpod-0"}, podGvk)
if err != nil {
fmt.Println("error getting pod from cache:", err)
}
fmt.Println("Pod:", pod)
fmt.Println("=================================")
fmt.Println("Pods in all namespaces:")
fmt.Println("=================================")
allList, _ := clusterCache.List(client.ListOptions{LabelSelector: labels.Everything()}, podGvk)
for _, obj := range allList {
podObj := obj.(*corev1.Pod)
fmt.Println("pod.Namespace:", podObj.Namespace, "pod.Name:", podObj.Name)
}
fmt.Println("=================================")
fmt.Println("Pods in kube-system namespace:")
fmt.Println("=================================")
allList, _ = clusterCache.List(client.ListOptions{LabelSelector: labels.Everything(), Namespace: "kube-system"}, podGvk)
for _, obj := range allList {
podObj := obj.(*corev1.Pod)
fmt.Println("pod.Namespace:", podObj.Namespace, "pod.Name:", podObj.Name)
}
fmt.Println("=================================")
}
// function for running stuff based on the namespaced cache
func namespacedCache() {
cfg := config.GetConfigOrDie()
namespacedCache := namespace.NewNamespaceScopedCache()
cli, err := client.New(cfg, client.Options{})
if err != nil {
fmt.Println("error creating client: %w", err)
os.Exit(2)
}
createResources(cli)
// create some informers
k8sClient := kubernetes.NewForConfigOrDie(cfg)
resync := 5 * time.Second
podGvk := corev1.SchemeGroupVersion.WithKind("Pod")
for i := 0; i < 6; i++ {
namespace := fmt.Sprintf("testns-%d", i)
// create a duplicate informer
if i == 5 {
namespace = "testns-0"
}
infFact := informers.NewSharedInformerFactoryWithOptions(k8sClient, resync, informers.WithNamespace(namespace))
podInf, err := infFact.ForResource(corev1.SchemeGroupVersion.WithResource("pods"))
if err != nil {
fmt.Println("error in getting pod informer for ns", namespace, "| error:", err)
continue
}
namespacedCache.AddInformer(components.InformerOptions{
Namespace: namespace,
Gvk: podGvk,
Key: "pod-informer",
Informer: podInf,
Dependent: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID(fmt.Sprintf("dependent-%d", i)),
},
},
})
}
fmt.Println("testns-0 pod informer dependents:", len(namespacedCache.Namespaces["testns-0"][podGvk]["pod-informer"].GetDependents()))
namespacedCache.Start()
// give resources time to populate
time.Sleep(10 * time.Second)
fmt.Println("Get Pod `testns-0/testpod-0`")
fmt.Println("=================================")
// get a pod
pod, err := namespacedCache.Get(types.NamespacedName{Namespace: "testns-0", Name: "testpod-0"}, podGvk)
if err != nil {
fmt.Println("error getting pod from cache:", err)
}
fmt.Println("Pod:", pod)
fmt.Println("=================================")
fmt.Println("Pods in all namespaces:")
fmt.Println("=================================")
allList, _ := namespacedCache.List(client.ListOptions{LabelSelector: labels.Everything()}, podGvk)
for _, obj := range allList {
podObj := obj.(*corev1.Pod)
fmt.Println("pod.Namespace:", podObj.Namespace, "pod.Name:", podObj.Name)
}
fmt.Println("=================================")
fmt.Println("Pods in `testns-0` namespace")
fmt.Println("=================================")
nsList, _ := namespacedCache.List(client.ListOptions{LabelSelector: labels.Everything(), Namespace: "testns-0"}, podGvk)
for _, obj := range nsList {
podObj := obj.(*corev1.Pod)
fmt.Println("pod.Namespace:", podObj.Namespace, "pod.Name:", podObj.Name)
}
fmt.Println("=================================")
}
// create some resources for testing
func createResources(cli client.Client) {
for i := 0; i < 5; i++ {
namespace := fmt.Sprintf("testns-%d", i)
err := cli.Create(context.TODO(), namespaceManifest(namespace))
if err != nil {
fmt.Println("error creating ns", namespace, "| error:", err)
}
for j := 0; j < 5; j++ {
podName := fmt.Sprintf("testpod-%d", j)
err = cli.Create(context.TODO(), podManifest(namespace, podName))
if err != nil {
fmt.Println("error creating pod", podName, "| error:", err)
}
}
}
}
func namespaceManifest(name string) *corev1.Namespace {
return &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
}
func podManifest(namespace string, name string) *corev1.Pod {
return &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: name,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "nginx",
Image: "nginx:1.14.2",
Ports: []corev1.ContainerPort{
{
ContainerPort: 80,
},
},
},
},
},
}
}