Jelajahi Sumber

Add utility updates and cluster info and map changes

Signed-off-by: Matt Bolt <mbolt35@gmail.com>
Matt Bolt 3 tahun lalu
induk
melakukan
f0f2356989

+ 8 - 8
pkg/costmodel/clusterinfo.go

@@ -24,23 +24,23 @@ var (
 
 // writeReportingFlags writes the reporting flags to the cluster info map
 func writeReportingFlags(clusterInfo map[string]string) {
-	clusterInfo["logCollection"] = fmt.Sprintf("%t", logCollectionEnabled)
-	clusterInfo["productAnalytics"] = fmt.Sprintf("%t", productAnalyticsEnabled)
-	clusterInfo["errorReporting"] = fmt.Sprintf("%t", errorReportingEnabled)
-	clusterInfo["valuesReporting"] = fmt.Sprintf("%t", valuesReportingEnabled)
+	clusterInfo[clusters.ClusterInfoLogCollectionKey] = fmt.Sprintf("%t", logCollectionEnabled)
+	clusterInfo[clusters.ClusterInfoProductAnalyticsKey] = fmt.Sprintf("%t", productAnalyticsEnabled)
+	clusterInfo[clusters.ClusterInfoErrorReportingKey] = fmt.Sprintf("%t", errorReportingEnabled)
+	clusterInfo[clusters.ClusterInfoValuesReportingKey] = fmt.Sprintf("%t", valuesReportingEnabled)
 }
 
 // writeClusterProfile writes the data associated with the cluster profile
 func writeClusterProfile(clusterInfo map[string]string) {
-	clusterInfo["clusterProfile"] = clusterProfile
+	clusterInfo[clusters.ClusterInfoProfileKey] = clusterProfile
 }
 
 // writeThanosFlags includes the configured thanos flags on the cluster info
 func writeThanosFlags(clusterInfo map[string]string) {
 	// Include Thanos Offset Duration if Applicable
-	clusterInfo["thanosEnabled"] = fmt.Sprintf("%t", thanos.IsEnabled())
+	clusterInfo[clusters.ClusterInfoThanosEnabledKey] = fmt.Sprintf("%t", thanos.IsEnabled())
 	if thanos.IsEnabled() {
-		clusterInfo["thanosOffset"] = thanos.Offset()
+		clusterInfo[clusters.ClusterInfoThanosOffsetKey] = thanos.Offset()
 	}
 }
 
@@ -65,7 +65,7 @@ func (dlcip *localClusterInfoProvider) GetClusterInfo() map[string]string {
 		if err != nil {
 			log.Infof("Could not get k8s version info: %s", err.Error())
 		} else if v != nil {
-			data["version"] = v.Major + "." + v.Minor
+			data[clusters.ClusterInfoVersionKey] = v.Major + "." + v.Minor
 		}
 	} else {
 		log.Infof("Could not get k8s version info: %s", err.Error())

+ 86 - 62
pkg/costmodel/clusters/clustermap.go

@@ -22,6 +22,25 @@ const (
 	LoadRetryDelay time.Duration = 10 * time.Second
 )
 
+// The following constants are used as keys into the cluster info map data structure
+const (
+	ClusterInfoIdKey               = "id"
+	ClusterInfoNameKey             = "name"
+	ClusterInfoProviderKey         = "provider"
+	ClusterInfoProjectKey          = "project"
+	ClusterInfoAccountKey          = "account"
+	ClusterInfoRegionKey           = "region"
+	ClusterInfoProvisionerKey      = "provisioner"
+	ClusterInfoProfileKey          = "clusterProfile"
+	ClusterInfoLogCollectionKey    = "logCollection"
+	ClusterInfoProductAnalyticsKey = "productAnalytics"
+	ClusterInfoErrorReportingKey   = "errorReporting"
+	ClusterInfoValuesReportingKey  = "valuesReporting"
+	ClusterInfoThanosEnabledKey    = "thanosEnabled"
+	ClusterInfoThanosOffsetKey     = "thanosOffset"
+	ClusterInfoVersionKey          = "version"
+)
+
 // prometheus query offset to apply to each non-range query
 // package scope to prevent calling duration parse each use
 var promQueryOffset = env.GetPrometheusQueryOffset()
@@ -73,12 +92,6 @@ type ClusterMap interface {
 	// NameIDFor returns an identifier in the format "<clusterName>/<clusterID>" if the cluster has an
 	// assigned name. Otherwise, just the clusterID is returned.
 	NameIDFor(clusterID string) string
-
-	// SplitNameID splits the nameID back into a separate id and name field
-	SplitNameID(nameID string) (id string, name string)
-
-	// StopRefresh stops the automatic internal map refresh
-	StopRefresh()
 }
 
 // ClusterInfoProvider is a contract which is capable of performing cluster info lookups.
@@ -89,7 +102,7 @@ type ClusterInfoProvider interface {
 
 // ClusterMap keeps records of all known cost-model clusters.
 type PrometheusClusterMap struct {
-	lock        *sync.RWMutex
+	lock        sync.RWMutex
 	client      prometheus.Client
 	clusters    map[string]*ClusterInfo
 	clusterInfo ClusterInfoProvider
@@ -101,7 +114,6 @@ func NewClusterMap(client prometheus.Client, cip ClusterInfoProvider, refresh ti
 	stop := make(chan struct{})
 
 	cm := &PrometheusClusterMap{
-		lock:        new(sync.RWMutex),
 		client:      client,
 		clusters:    make(map[string]*ClusterInfo),
 		clusterInfo: cip,
@@ -233,61 +245,12 @@ func (pcm *PrometheusClusterMap) loadClusters() (map[string]*ClusterInfo, error)
 func (pcm *PrometheusClusterMap) getLocalClusterInfo() (*ClusterInfo, error) {
 	info := pcm.clusterInfo.GetClusterInfo()
 
-	var id string
-	var name string
-
-	if i, ok := info["id"]; ok {
-		id = i
-	} else {
-		return nil, fmt.Errorf("Local Cluster Info Missing ID")
-	}
-	if n, ok := info["name"]; ok {
-		name = n
-	} else {
-		return nil, fmt.Errorf("Local Cluster Info Missing Name")
-	}
-
-	var clusterProfile string
-	var provider string
-	var account string
-	var project string
-	var region string
-	var provisioner string
-
-	if cp, ok := info["clusterProfile"]; ok {
-		clusterProfile = cp
-	}
-
-	if pvdr, ok := info["provider"]; ok {
-		provider = pvdr
-	}
-
-	if acct, ok := info["account"]; ok {
-		account = acct
-	}
-
-	if proj, ok := info["project"]; ok {
-		project = proj
-	}
-
-	if reg, ok := info["region"]; ok {
-		region = reg
-	}
-
-	if pvsr, ok := info["provisioner"]; ok {
-		provisioner = pvsr
+	clusterInfo, err := MapToClusterInfo(info)
+	if err != nil {
+		return nil, fmt.Errorf("Parsing Local Cluster Info Failed: %s", err)
 	}
 
-	return &ClusterInfo{
-		ID:          id,
-		Name:        name,
-		Profile:     clusterProfile,
-		Provider:    provider,
-		Account:     account,
-		Project:     project,
-		Region:      region,
-		Provisioner: provisioner,
-	}, nil
+	return clusterInfo, nil
 }
 
 // refreshClusters loads the clusters and updates the internal map
@@ -371,7 +334,8 @@ func (pcm *PrometheusClusterMap) NameIDFor(clusterID string) string {
 	return clusterID
 }
 
-func (pcm *PrometheusClusterMap) SplitNameID(nameID string) (id string, name string) {
+// SplitNameID is a helper method that removes the common split format and returns
+func SplitNameID(nameID string) (id string, name string) {
 	if !strings.Contains(nameID, "/") {
 		id = nameID
 		name = ""
@@ -391,3 +355,63 @@ func (pcm *PrometheusClusterMap) StopRefresh() {
 		pcm.stop = nil
 	}
 }
+
+// MapToClusterInfo returns a ClusterInfo using parsed data from a string map. If
+// parsing the map fails for id and/or name, an error is returned.
+func MapToClusterInfo(info map[string]string) (*ClusterInfo, error) {
+	var id string
+	var name string
+
+	if i, ok := info[ClusterInfoIdKey]; ok {
+		id = i
+	} else {
+		return nil, fmt.Errorf("Cluster Info Missing ID")
+	}
+	if n, ok := info[ClusterInfoNameKey]; ok {
+		name = n
+	} else {
+		name = id
+	}
+
+	var clusterProfile string
+	var provider string
+	var account string
+	var project string
+	var region string
+	var provisioner string
+
+	if cp, ok := info[ClusterInfoProfileKey]; ok {
+		clusterProfile = cp
+	}
+
+	if pvdr, ok := info[ClusterInfoProviderKey]; ok {
+		provider = pvdr
+	}
+
+	if acct, ok := info[ClusterInfoAccountKey]; ok {
+		account = acct
+	}
+
+	if proj, ok := info[ClusterInfoProjectKey]; ok {
+		project = proj
+	}
+
+	if reg, ok := info[ClusterInfoRegionKey]; ok {
+		region = reg
+	}
+
+	if pvsr, ok := info[ClusterInfoProvisionerKey]; ok {
+		provisioner = pvsr
+	}
+
+	return &ClusterInfo{
+		ID:          id,
+		Name:        name,
+		Profile:     clusterProfile,
+		Provider:    provider,
+		Account:     account,
+		Project:     project,
+		Region:      region,
+		Provisioner: provisioner,
+	}, nil
+}

+ 11 - 0
pkg/util/maputil/maputil.go

@@ -0,0 +1,11 @@
+package maputil
+
+// Map applies a transformation function to each value within a map to get a new map containing the
+// transformed values.
+func Map[K comparable, V any, T any](m map[K]V, transform func(V) T) map[K]T {
+	result := make(map[K]T, len(m))
+	for k, v := range m {
+		result[k] = transform(v)
+	}
+	return result
+}

+ 11 - 0
pkg/util/sliceutil/sliceutil.go

@@ -0,0 +1,11 @@
+package sliceutil
+
+// Map accepts a slice of T and applies a transformation function to each index of a
+// slice, which are inserted into a new slice of type U.
+func Map[T any, U any](s []T, transform func(T) U) []U {
+	result := make([]U, len(s))
+	for i := 0; i < len(s); i++ {
+		result[i] = transform(s[i])
+	}
+	return result
+}