github.com/banzaicloud/operator-tools@v0.28.10/pkg/inventory/scope.go (about) 1 // Copyright © 2020 Banzai Cloud 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 inventory 16 17 import ( 18 "sync" 19 20 "emperror.dev/errors" 21 "k8s.io/apimachinery/pkg/runtime/schema" 22 "k8s.io/client-go/discovery" 23 ) 24 25 var staticResourceScope map[string]bool 26 var dynamicResourceScope map[string]bool 27 28 var mutex = sync.RWMutex{} 29 30 func AddStaticResourceScope(gk schema.GroupKind, namespaced bool) { 31 mutex.Lock() 32 defer mutex.Unlock() 33 34 if staticResourceScope == nil { 35 staticResourceScope = make(map[string]bool) 36 } 37 staticResourceScope[gk.String()] = namespaced 38 } 39 40 func getStaticResourceScope(gk schema.GroupKind) (bool, bool) { 41 mutex.RLock() 42 defer mutex.RUnlock() 43 44 namespaced, ok := staticResourceScope[gk.String()] 45 return namespaced, ok 46 } 47 48 // initializeAPIResources discovers api resources and returns true if initialization actually happened 49 func initializeAPIResources(discoveryClient discovery.DiscoveryInterface) (bool, error) { 50 if len(dynamicResourceScope) == 0 { 51 return true, discoverAPIResources(discoveryClient) 52 } 53 return false, nil 54 } 55 56 func discoverAPIResources(discoveryClient discovery.DiscoveryInterface) error { 57 mutex.Lock() 58 defer mutex.Unlock() 59 60 _, apiResourcesList, err := discoveryClient.ServerGroupsAndResources() 61 if err != nil { 62 return errors.WrapIf(err, "couldn't retrieve the list of resources supported by API server") 63 } 64 for _, apiResources := range apiResourcesList { 65 if apiResources != nil { 66 gv, err := schema.ParseGroupVersion(apiResources.GroupVersion) 67 if err != nil { 68 return errors.WrapIff(err, "unable to parse groupversion %s", apiResources.GroupVersion) 69 } 70 for _, apiResource := range apiResources.APIResources { 71 gk := schema.GroupKind{Group: gv.Group, Kind: apiResource.Kind} 72 if dynamicResourceScope == nil { 73 dynamicResourceScope = make(map[string]bool) 74 } 75 dynamicResourceScope[gk.String()] = apiResource.Namespaced 76 } 77 } 78 } 79 return nil 80 } 81 82 // getDynamicResourceScope returns 83 func getDynamicResourceScope(gk schema.GroupKind) (bool, bool) { 84 mutex.RLock() 85 defer mutex.RUnlock() 86 87 namespaced, ok := dynamicResourceScope[gk.String()] 88 return namespaced, ok 89 }