istio.io/istio@v0.0.0-20240520182934-d79c90f27776/operator/pkg/cache/cache.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cache 16 17 import ( 18 "sync" 19 20 "istio.io/istio/operator/pkg/metrics" 21 "istio.io/istio/operator/pkg/object" 22 ) 23 24 // ObjectCache is a cache of objects, 25 type ObjectCache struct { 26 // Cache is a cache keyed by object Hash() function. 27 Cache map[string]*object.K8sObject 28 Mu *sync.RWMutex 29 } 30 31 var ( 32 // objectCaches holds the latest copy of each object applied by the controller. The caches are divided by component 33 // name. 34 objectCaches = make(map[string]*ObjectCache) 35 objectCachesMu sync.RWMutex 36 ) 37 38 // FlushObjectCaches flushes all object caches. 39 func FlushObjectCaches() { 40 objectCachesMu.Lock() 41 defer objectCachesMu.Unlock() 42 objectCaches = make(map[string]*ObjectCache) 43 metrics.CacheFlushTotal.Increment() 44 } 45 46 // GetCache returns the object Cache for the given name, creating one in the global Cache if needed. 47 func GetCache(name string) *ObjectCache { 48 objectCachesMu.Lock() 49 defer objectCachesMu.Unlock() 50 51 // Create and/or get the Cache corresponding to the CR name we're processing. Per name partitioning is required to 52 // prune the Cache to remove any objects not in the manifest generated for a given CR. 53 if objectCaches[name] == nil { 54 objectCaches[name] = &ObjectCache{ 55 Cache: make(map[string]*object.K8sObject), 56 Mu: &sync.RWMutex{}, 57 } 58 } 59 return objectCaches[name] 60 } 61 62 // RemoveObject removes object with objHash in the Cache with the given name from the object Cache. 63 func RemoveObject(name, objHash string) { 64 objectCachesMu.RLock() 65 objectCache := objectCaches[name] 66 objectCachesMu.RUnlock() 67 68 if objectCache != nil { 69 objectCache.Mu.Lock() 70 delete(objectCache.Cache, objHash) 71 objectCache.Mu.Unlock() 72 } 73 } 74 75 // RemoveCache removes the object Cache with the give name. 76 func RemoveCache(name string) { 77 objectCachesMu.Lock() 78 defer objectCachesMu.Unlock() 79 80 delete(objectCaches, name) 81 }