github.com/verrazzano/verrazzano@v1.7.0/tools/vz/pkg/analysis/internal/util/cluster/services.go (about) 1 // Copyright (c) 2021, 2022, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 // Package cluster handles cluster analysis 5 package cluster 6 7 import ( 8 encjson "encoding/json" 9 "go.uber.org/zap" 10 "io" 11 corev1 "k8s.io/api/core/v1" 12 "os" 13 "sync" 14 ) 15 16 // serviceListMap holds serviceLists which have been read in already 17 var serviceListMap = make(map[string]*corev1.ServiceList) 18 var serviceCacheMutex = &sync.Mutex{} 19 20 // GetServiceList gets a service list 21 func GetServiceList(log *zap.SugaredLogger, path string) (serviceList *corev1.ServiceList, err error) { 22 // Check the cache first 23 serviceList = getServiceListIfPresent(path) 24 if serviceList != nil { 25 log.Debugf("Returning cached serviceList for %s", path) 26 return serviceList, nil 27 } 28 29 // Not found in the cache, get it from the file 30 file, err := os.Open(path) 31 if err != nil { 32 log.Debugf("file %s not found", path) 33 return nil, err 34 } 35 defer file.Close() 36 37 fileBytes, err := io.ReadAll(file) 38 if err != nil { 39 log.Debugf("Failed reading Json file %s", path) 40 return nil, err 41 } 42 err = encjson.Unmarshal(fileBytes, &serviceList) 43 if err != nil { 44 log.Debugf("Failed to unmarshal serviceList at %s", path) 45 return nil, err 46 } 47 putServiceListIfNotPresent(path, serviceList) 48 return serviceList, nil 49 } 50 51 func getServiceListIfPresent(path string) (serviceList *corev1.ServiceList) { 52 serviceCacheMutex.Lock() 53 serviceListTest := serviceListMap[path] 54 if serviceListTest != nil { 55 serviceList = serviceListTest 56 } 57 serviceCacheMutex.Unlock() 58 return serviceList 59 } 60 61 func putServiceListIfNotPresent(path string, serviceList *corev1.ServiceList) { 62 serviceCacheMutex.Lock() 63 serviceListInMap := serviceListMap[path] 64 if serviceListInMap == nil { 65 serviceListMap[path] = serviceList 66 } 67 serviceCacheMutex.Unlock() 68 }