github.com/jenkins-x/jx/v2@v2.1.155/pkg/kube/env_cache.go (about) 1 package kube 2 3 import ( 4 "sort" 5 "time" 6 7 v1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1" 8 "github.com/jenkins-x/jx-api/pkg/client/clientset/versioned" 9 "github.com/jenkins-x/jx-logging/pkg/log" 10 "k8s.io/apimachinery/pkg/fields" 11 "k8s.io/client-go/tools/cache" 12 ) 13 14 // EnvironmentNamespaceCache caches the Environments for a single namespace 15 type EnvironmentNamespaceCache struct { 16 items map[string]*v1.Environment 17 } 18 19 // CreateEnvironmentCache creates a cache for the given namespace of Environments 20 func CreateEnvironmentCache(jxClient versioned.Interface, ns string) *EnvironmentNamespaceCache { 21 Environment := &v1.Environment{} 22 stop := make(chan struct{}) 23 environmentListWatch := cache.NewListWatchFromClient(jxClient.JenkinsV1().RESTClient(), "environments", ns, fields.Everything()) 24 25 namespaceCache := &EnvironmentNamespaceCache{ 26 items: map[string]*v1.Environment{}, 27 } 28 29 _, EnvironmentController := cache.NewInformer( 30 environmentListWatch, 31 Environment, 32 time.Minute*10, 33 cache.ResourceEventHandlerFuncs{ 34 AddFunc: func(obj interface{}) { 35 namespaceCache.onEnvironmentObj(obj, jxClient, ns) 36 }, 37 UpdateFunc: func(oldObj, newObj interface{}) { 38 namespaceCache.onEnvironmentObj(newObj, jxClient, ns) 39 }, 40 DeleteFunc: func(obj interface{}) { 41 namespaceCache.onEnvironmentDelete(obj, jxClient, ns) 42 }, 43 }, 44 ) 45 46 go EnvironmentController.Run(stop) 47 48 return namespaceCache 49 } 50 51 // Items returns the Environments in this namespace sorted in name order 52 func (c *EnvironmentNamespaceCache) Items() []*v1.Environment { 53 answer := []*v1.Environment{} 54 names := []string{} 55 for k := range c.items { 56 names = append(names, k) 57 } 58 sort.Strings(names) 59 for _, name := range names { 60 Environment := c.items[name] 61 if Environment != nil { 62 answer = append(answer, Environment) 63 } 64 } 65 return answer 66 } 67 68 // Item returns the Environment for the tiven name 69 func (c *EnvironmentNamespaceCache) Item(name string) *v1.Environment { 70 return c.items[name] 71 } 72 73 func (c *EnvironmentNamespaceCache) onEnvironmentObj(obj interface{}, jxClient versioned.Interface, ns string) { 74 Environment, ok := obj.(*v1.Environment) 75 if !ok { 76 log.Logger().Warnf("Object is not a Environment %#v", obj) 77 return 78 } 79 if Environment != nil { 80 c.items[Environment.Name] = Environment 81 } 82 } 83 84 func (c *EnvironmentNamespaceCache) onEnvironmentDelete(obj interface{}, jxClient versioned.Interface, ns string) { 85 Environment, ok := obj.(*v1.Environment) 86 if !ok { 87 log.Logger().Warnf("Object is not a Environment %#v", obj) 88 return 89 } 90 if Environment != nil { 91 delete(c.items, Environment.Name) 92 } 93 }