forked from kiali/kiali
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
459 lines (425 loc) · 13.1 KB
/
cache.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package kubernetes
import (
"errors"
"fmt"
"sync"
"time"
"k8s.io/api/apps/v1beta1"
"k8s.io/api/apps/v1beta2"
batch_v1 "k8s.io/api/batch/v1"
batch_v1beta1 "k8s.io/api/batch/v1beta1"
"k8s.io/api/core/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/informers"
kube "k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"github.com/kiali/kiali/log"
)
type (
// Inspired/reused from istio code:
// https://github.com/istio/istio/blob/master/mixer/adapter/kubernetesenv/cache.go
cacheController interface {
// Control Cache
Start()
HasSynced() bool
WaitForSync() bool
Stop()
// Business methods
GetCronJobs(namespace string) ([]batch_v1beta1.CronJob, error)
GetDeployment(namespace string, name string) (*v1beta1.Deployment, error)
GetDeployments(namespace string) ([]v1beta1.Deployment, error)
GetEndpoints(namespace, name string) (*v1.Endpoints, error)
GetJobs(namespace string) ([]batch_v1.Job, error)
GetPods(namespace string) ([]v1.Pod, error)
GetReplicationControllers(namespace string) ([]v1.ReplicationController, error)
GetReplicaSets(namespace string) ([]v1beta2.ReplicaSet, error)
GetService(namespace string, name string) (*v1.Service, error)
GetServices(namespace string) ([]v1.Service, error)
GetStatefulSet(namespace string, name string) (*v1beta2.StatefulSet, error)
GetStatefulSets(namespace string) ([]v1beta2.StatefulSet, error)
}
controllerImpl struct {
clientset kube.Interface
refreshDuration time.Duration
stopChan chan struct{}
syncCount int
maxSyncCount int
isErrorState bool
lastError error
lastErrorLock sync.Mutex
controllers map[string]cache.SharedIndexInformer
}
)
var (
lastCacheErrorLock sync.Mutex
errorCallbacks []func(error)
)
func init() {
setupErrorHandlers()
errorCallbacks = make([]func(error), 0)
}
func setupErrorHandlers() {
nErrFunc := len(utilruntime.ErrorHandlers)
customErrorHandler := make([]func(error), nErrFunc+1)
for i, errorFunc := range utilruntime.ErrorHandlers {
customErrorHandler[i] = errorFunc
}
customErrorHandler[nErrFunc] = func(err error) {
for _, callback := range errorCallbacks {
callback(err)
}
}
utilruntime.ErrorHandlers = customErrorHandler
}
func registerErrorCallback(callback func(error)) {
defer lastCacheErrorLock.Unlock()
lastCacheErrorLock.Lock()
errorCallbacks = append(errorCallbacks, callback)
}
func newCacheController(clientset kube.Interface, refreshDuration time.Duration) cacheController {
newControllerImpl := controllerImpl{
clientset: clientset,
refreshDuration: refreshDuration,
stopChan: nil,
controllers: initControllers(clientset, refreshDuration),
syncCount: 0,
maxSyncCount: 20, // Move this to config ? or this constant is good enough ?
}
registerErrorCallback(newControllerImpl.ErrorCallback)
return &newControllerImpl
}
func initControllers(clientset kube.Interface, refreshDuration time.Duration) map[string]cache.SharedIndexInformer {
sharedInformers := informers.NewSharedInformerFactory(clientset, refreshDuration)
controllers := make(map[string]cache.SharedIndexInformer)
controllers["Pod"] = sharedInformers.Core().V1().Pods().Informer()
controllers["ReplicationController"] = sharedInformers.Core().V1().ReplicationControllers().Informer()
controllers["Deployment"] = sharedInformers.Apps().V1beta1().Deployments().Informer()
controllers["ReplicaSet"] = sharedInformers.Apps().V1beta2().ReplicaSets().Informer()
controllers["StatefulSet"] = sharedInformers.Apps().V1beta2().StatefulSets().Informer()
controllers["Job"] = sharedInformers.Batch().V1().Jobs().Informer()
controllers["CronJob"] = sharedInformers.Batch().V1beta1().CronJobs().Informer()
controllers["Service"] = sharedInformers.Core().V1().Services().Informer()
controllers["Endpoints"] = sharedInformers.Core().V1().Endpoints().Informer()
return controllers
}
func (c *controllerImpl) Start() {
if c.stopChan == nil {
c.stopChan = make(chan struct{})
go c.run(c.stopChan)
log.Infof("K8S cache started")
} else {
log.Warningf("K8S cache is already running")
}
}
func (c *controllerImpl) run(stop <-chan struct{}) {
for _, cn := range c.controllers {
go cn.Run(stop)
}
<-stop
log.Infof("K8S cache stopped")
}
func (c *controllerImpl) HasSynced() bool {
if c.syncCount > c.maxSyncCount {
log.Errorf("Max attempts reached syncing cache. Error connecting to k8s API: %d > %d", c.syncCount, c.maxSyncCount)
c.Stop()
return false
}
hasSynced := true
for _, cn := range c.controllers {
hasSynced = hasSynced && cn.HasSynced()
}
if hasSynced {
c.syncCount = 0
} else {
c.syncCount = c.syncCount + 1
}
return hasSynced
}
func (c *controllerImpl) WaitForSync() bool {
return cache.WaitForCacheSync(c.stopChan, c.HasSynced)
}
func (c *controllerImpl) Stop() {
if c.stopChan != nil {
close(c.stopChan)
c.stopChan = nil
}
}
func (c *controllerImpl) ErrorCallback(err error) {
if c.isErrorState == false {
log.Warningf("Error callback received: %s", err)
c.lastErrorLock.Lock()
c.isErrorState = true
c.lastError = err
c.lastErrorLock.Unlock()
c.Stop()
}
}
func (c *controllerImpl) checkStateAndRetry() error {
if c.isErrorState == false {
return nil
}
// Retry of the cache is hold by one single goroutine
c.lastErrorLock.Lock()
if c.isErrorState == true {
// ping to check if backend is still unavailable (used namespace endpoint)
_, err := c.clientset.CoreV1().Namespaces().List(emptyListOptions)
if err != nil {
c.lastError = fmt.Errorf("Error retrying to connect to K8S API backend. %s", err)
} else {
c.lastError = nil
c.isErrorState = false
c.Start()
c.WaitForSync()
}
}
c.lastErrorLock.Unlock()
return c.lastError
}
func (c *controllerImpl) GetCronJobs(namespace string) ([]batch_v1beta1.CronJob, error) {
if err := c.checkStateAndRetry(); err != nil {
return []batch_v1beta1.CronJob{}, err
}
indexer := c.controllers["CronJob"].GetIndexer()
cronjobs, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []batch_v1beta1.CronJob{}, err
}
if len(cronjobs) > 0 {
_, ok := cronjobs[0].(*batch_v1beta1.CronJob)
if !ok {
return []batch_v1beta1.CronJob{}, errors.New("Bad CronJob type found in cache")
}
nsCronjobs := make([]batch_v1beta1.CronJob, len(cronjobs))
for i, cronjob := range cronjobs {
nsCronjobs[i] = *(cronjob.(*batch_v1beta1.CronJob))
}
return nsCronjobs, nil
}
return []batch_v1beta1.CronJob{}, nil
}
func (c *controllerImpl) GetDeployment(namespace, name string) (*v1beta1.Deployment, error) {
if err := c.checkStateAndRetry(); err != nil {
return nil, err
}
indexer := c.controllers["Deployment"].GetIndexer()
deps, exist, err := indexer.GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if exist {
dep, ok := deps.(*v1beta1.Deployment)
if !ok {
return nil, errors.New("Bad Deployment type found in cache")
}
return dep, nil
}
return nil, NewNotFound(name, "apps/v1beta1", "Deployment")
}
func (c *controllerImpl) GetDeployments(namespace string) ([]v1beta1.Deployment, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1beta1.Deployment{}, err
}
indexer := c.controllers["Deployment"].GetIndexer()
deps, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1beta1.Deployment{}, err
}
if len(deps) > 0 {
_, ok := deps[0].(*v1beta1.Deployment)
if !ok {
return nil, errors.New("Bad Deployment type found in cache")
}
nsDeps := make([]v1beta1.Deployment, len(deps))
for i, dep := range deps {
nsDeps[i] = *(dep.(*v1beta1.Deployment))
}
return nsDeps, nil
}
return []v1beta1.Deployment{}, nil
}
func (c *controllerImpl) GetEndpoints(namespace, name string) (*v1.Endpoints, error) {
if err := c.checkStateAndRetry(); err != nil {
return nil, err
}
indexer := c.controllers["Endpoints"].GetIndexer()
endpoints, exist, err := indexer.GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if exist {
endpoint, ok := endpoints.(*v1.Endpoints)
if !ok {
return nil, errors.New("Bad Endpoints type found in cache")
}
return endpoint, nil
}
return nil, NewNotFound(name, "core/v1", "Endpoints")
}
func (c *controllerImpl) GetJobs(namespace string) ([]batch_v1.Job, error) {
if err := c.checkStateAndRetry(); err != nil {
return []batch_v1.Job{}, err
}
indexer := c.controllers["Job"].GetIndexer()
jobs, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []batch_v1.Job{}, err
}
if len(jobs) > 0 {
_, ok := jobs[0].(*batch_v1.Job)
if !ok {
return []batch_v1.Job{}, errors.New("Bad Job type found in cache")
}
nsJobs := make([]batch_v1.Job, len(jobs))
for i, job := range jobs {
nsJobs[i] = *(job.(*batch_v1.Job))
}
return nsJobs, nil
}
return []batch_v1.Job{}, nil
}
func (c *controllerImpl) GetPods(namespace string) ([]v1.Pod, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1.Pod{}, err
}
indexer := c.controllers["Pod"].GetIndexer()
pods, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1.Pod{}, err
}
if len(pods) > 0 {
_, ok := pods[0].(*v1.Pod)
if !ok {
return []v1.Pod{}, errors.New("Bad Pod type found in cache")
}
nsPods := make([]v1.Pod, len(pods))
for i, pod := range pods {
nsPods[i] = *(pod.(*v1.Pod))
}
return nsPods, nil
}
return []v1.Pod{}, nil
}
func (c *controllerImpl) GetReplicationControllers(namespace string) ([]v1.ReplicationController, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1.ReplicationController{}, err
}
indexer := c.controllers["ReplicationController"].GetIndexer()
repcons, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1.ReplicationController{}, err
}
if len(repcons) > 0 {
_, ok := repcons[0].(*v1.ReplicationController)
if !ok {
return []v1.ReplicationController{}, errors.New("Bad ReplicationController type found in cache")
}
nsRepcons := make([]v1.ReplicationController, len(repcons))
for i, repcon := range repcons {
nsRepcons[i] = *(repcon.(*v1.ReplicationController))
}
return nsRepcons, nil
}
return []v1.ReplicationController{}, nil
}
func (c *controllerImpl) GetReplicaSets(namespace string) ([]v1beta2.ReplicaSet, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1beta2.ReplicaSet{}, err
}
indexer := c.controllers["ReplicaSet"].GetIndexer()
repsets, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1beta2.ReplicaSet{}, err
}
if len(repsets) > 0 {
_, ok := repsets[0].(*v1beta2.ReplicaSet)
if !ok {
return []v1beta2.ReplicaSet{}, errors.New("Bad ReplicaSet type found in cache")
}
nsRepsets := make([]v1beta2.ReplicaSet, len(repsets))
for i, repset := range repsets {
nsRepsets[i] = *(repset.(*v1beta2.ReplicaSet))
}
return nsRepsets, nil
}
return []v1beta2.ReplicaSet{}, nil
}
func (c *controllerImpl) GetStatefulSet(namespace, name string) (*v1beta2.StatefulSet, error) {
if err := c.checkStateAndRetry(); err != nil {
return nil, err
}
indexer := c.controllers["StatefulSet"].GetIndexer()
fulsets, exist, err := indexer.GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if exist {
fulset, ok := fulsets.(*v1beta2.StatefulSet)
if !ok {
return nil, errors.New("Bad StatefulSet type found in cache")
}
return fulset, nil
}
return nil, NewNotFound(name, "apps/v1beta2", "StatefulSet")
}
func (c *controllerImpl) GetStatefulSets(namespace string) ([]v1beta2.StatefulSet, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1beta2.StatefulSet{}, err
}
indexer := c.controllers["StatefulSet"].GetIndexer()
fulsets, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1beta2.StatefulSet{}, err
}
if len(fulsets) > 0 {
_, ok := fulsets[0].(*v1beta2.StatefulSet)
if !ok {
return []v1beta2.StatefulSet{}, errors.New("Bad StatefulSet type found in cache")
}
nsFulsets := make([]v1beta2.StatefulSet, len(fulsets))
for i, fulset := range fulsets {
nsFulsets[i] = *(fulset.(*v1beta2.StatefulSet))
}
return nsFulsets, nil
}
return []v1beta2.StatefulSet{}, nil
}
func (c *controllerImpl) GetService(namespace, name string) (*v1.Service, error) {
if err := c.checkStateAndRetry(); err != nil {
return nil, err
}
indexer := c.controllers["Service"].GetIndexer()
services, exist, err := indexer.GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if exist {
service, ok := services.(*v1.Service)
if !ok {
return nil, errors.New("Bad Service type found in cache")
}
return service, nil
}
return nil, NewNotFound(name, "core/v1", "Service")
}
func (c *controllerImpl) GetServices(namespace string) ([]v1.Service, error) {
if err := c.checkStateAndRetry(); err != nil {
return []v1.Service{}, err
}
indexer := c.controllers["Service"].GetIndexer()
services, err := indexer.ByIndex("namespace", namespace)
if err != nil {
return []v1.Service{}, err
}
if len(services) > 0 {
_, ok := services[0].(*v1.Service)
if !ok {
return []v1.Service{}, errors.New("Bad Service type found in cache")
}
nsServices := make([]v1.Service, len(services))
for i, service := range services {
nsServices[i] = *(service.(*v1.Service))
}
return nsServices, nil
}
return []v1.Service{}, nil
}