-
Notifications
You must be signed in to change notification settings - Fork 787
/
env_cache.go
92 lines (81 loc) · 2.5 KB
/
env_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
package kube
import (
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/log"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/tools/cache"
"sort"
"time"
)
// EnvironmentNamespaceCache caches the Environments for a single namespace
type EnvironmentNamespaceCache struct {
items map[string]*v1.Environment
}
// CreateEnvironmentCache creates a cache for the given namespace of Environments
func CreateEnvironmentCache(jxClient versioned.Interface, ns string) *EnvironmentNamespaceCache {
Environment := &v1.Environment{}
stop := make(chan struct{})
environmentListWatch := cache.NewListWatchFromClient(jxClient.JenkinsV1().RESTClient(), "environments", ns, fields.Everything())
namespaceCache := &EnvironmentNamespaceCache{
items: map[string]*v1.Environment{},
}
_, EnvironmentController := cache.NewInformer(
environmentListWatch,
Environment,
time.Minute*10,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
namespaceCache.onEnvironmentObj(obj, jxClient, ns)
},
UpdateFunc: func(oldObj, newObj interface{}) {
namespaceCache.onEnvironmentObj(newObj, jxClient, ns)
},
DeleteFunc: func(obj interface{}) {
namespaceCache.onEnvironmentDelete(obj, jxClient, ns)
},
},
)
go EnvironmentController.Run(stop)
return namespaceCache
}
// Items returns the Environments in this namespace sorted in name order
func (c *EnvironmentNamespaceCache) Items() []*v1.Environment {
answer := []*v1.Environment{}
names := []string{}
for k := range c.items {
names = append(names, k)
}
sort.Strings(names)
for _, name := range names {
Environment := c.items[name]
if Environment != nil {
answer = append(answer, Environment)
}
}
return answer
}
// Item returns the Environment for the tiven name
func (c *EnvironmentNamespaceCache) Item(name string) *v1.Environment {
return c.items[name]
}
func (c *EnvironmentNamespaceCache) onEnvironmentObj(obj interface{}, jxClient versioned.Interface, ns string) {
Environment, ok := obj.(*v1.Environment)
if !ok {
log.Warnf("Object is not a Environment %#v\n", obj)
return
}
if Environment != nil {
c.items[Environment.Name] = Environment
}
}
func (c *EnvironmentNamespaceCache) onEnvironmentDelete(obj interface{}, jxClient versioned.Interface, ns string) {
Environment, ok := obj.(*v1.Environment)
if !ok {
log.Warnf("Object is not a Environment %#v\n", obj)
return
}
if Environment != nil {
delete(c.items, Environment.Name)
}
}