Pārlūkot izejas kodu

Flush cache when custom pricing changes

Niko Kovacevic 6 gadi atpakaļ
vecāks
revīzija
0237e3f675
1 mainītis faili ar 42 papildinājumiem un 0 dzēšanām
  1. 42 0
      costmodel/router.go

+ 42 - 0
costmodel/router.go

@@ -64,6 +64,7 @@ type Accesses struct {
 	Model                         *CostModel
 	AggregateCache                *cache.Cache
 	CostDataCache                 *cache.Cache
+	CustomPricingCache            *cache.Cache
 	OutOfClusterCache             *cache.Cache
 }
 
@@ -325,6 +326,41 @@ func (a *Accesses) ClusterCostsOverTime(w http.ResponseWriter, r *http.Request,
 	w.Write(wrapData(data, err))
 }
 
+func (a *Accesses) CustomPricingHasChanged() bool {
+	customPricing, err := a.Cloud.GetConfig()
+	if err != nil {
+		klog.Errorf("error accessing cloud provider configuration: %s", err)
+		return false
+	}
+
+	// describe parameters by which we determine whether or not custom
+	// pricing settings have changed
+	encodeCustomPricing := func(cp *costAnalyzerCloud.CustomPricing) string {
+		return fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s", cp.CustomPricesEnabled, cp.CPU, cp.SpotCPU,
+			cp.RAM, cp.SpotRAM, cp.GPU, cp.Storage)
+	}
+
+	// compare cached custom pricing parameters with current values
+	cpStr := encodeCustomPricing(customPricing)
+	cpStrCached := ""
+	val, found := a.CustomPricingCache.Get("customPricing")
+	if found {
+		ok := false
+		cpStrCached, ok = val.(string)
+		if !ok {
+			klog.Errorf("caching error: failed to cast custom pricing to string")
+		}
+	}
+	if cpStr == cpStrCached {
+		return false
+	}
+
+	// cache new custom pricing settings
+	a.CustomPricingCache.Set("customPricing", cpStr, cache.DefaultExpiration)
+
+	return true
+}
+
 // AggregateCostModel handles HTTP requests to the aggregated cost model API, which can be parametrized
 // by time period using window and offset, aggregation field and subfield (e.g. grouping by label.app
 // using aggregation=label, aggregationSubfield=app), and filtered by namespace and cluster.
@@ -386,6 +422,12 @@ func (a *Accesses) AggregateCostModel(w http.ResponseWriter, r *http.Request, ps
 		return
 	}
 
+	// if custom pricing has changed, then clear the cache and recompute data
+	if a.CustomPricingHasChanged() {
+		klog.V(1).Infof("detected custom pricing change, flushing cache")
+		clearCache = true
+	}
+
 	// clear cache prior to checking the cache so that a clearCache=true
 	// request always returns a freshly computed value
 	if clearCache {