2
0
Эх сурвалжийг харах

Environment variables and tests for supporting without Kubernetes

Signed-off-by: Matt Ray <github@mattray.dev>
Matt Ray 2 жил өмнө
parent
commit
1c68af96b4

+ 8 - 0
pkg/cloud/config/watcher.go

@@ -30,6 +30,7 @@ type HelmWatcher struct {
 // only one billing integration due to values being shared by different configuration types.
 func (hw *HelmWatcher) GetConfigs() []cloud.KeyedConfig {
 	var configs []cloud.KeyedConfig
+	log.Info("+++HelmWatcher GetConfigs")
 
 	customPricing, _ := hw.providerConfig.GetCustomPricingData()
 
@@ -149,6 +150,8 @@ type ConfigFileWatcher struct {
 func (cfw *ConfigFileWatcher) GetConfigs() []cloud.KeyedConfig {
 	var configs []cloud.KeyedConfig
 
+	log.Info("+++ConfigFileWatcher GetConfigs")
+
 	customPricing, _ := cfw.providerConfig.GetCustomPricingData()
 
 	// Detect Azure Storage configuration
@@ -239,7 +242,12 @@ type MultiCloudWatcher struct {
 }
 
 func (mcw *MultiCloudWatcher) GetConfigs() []cloud.KeyedConfig {
+	log.Info("+++MultiCloudWatcher GetConfigs")
+
 	multiConfigPath := path.Join(env.GetConfigPathWithDefault("/var/configs"), cloudIntegrationSecretPath)
+
+	log.Infof("+++ConfigFileWatcher GetConfigs: multiConfigPath: %s", multiConfigPath)
+
 	exists, err := fileutil.FileExists(multiConfigPath)
 	if err != nil {
 		log.Errorf("MultiCloudWatcher:  error checking file at '%s': %s", multiConfigPath, err.Error())

+ 18 - 7
pkg/cmd/costmodel/costmodel.go

@@ -34,15 +34,23 @@ func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
 
 func Execute(opts *CostModelOpts) error {
 	log.Infof("Starting cost-model version %s", version.FriendlyVersion())
-	a := costmodel.Initialize()
+	log.Infof("Kubernetes enabled: %t", env.IsKubernetesEnabled())
+	a := costmodel.InitializeWithoutKubernetes()
 
-	err := StartExportWorker(context.Background(), a.Model)
-	if err != nil {
-		log.Errorf("couldn't start CSV export worker: %v", err)
+	if env.IsKubernetesEnabled() {
+		a := costmodel.Initialize()
+
+		err := StartExportWorker(context.Background(), a.Model)
+		if err != nil {
+			log.Errorf("couldn't start CSV export worker: %v", err)
+		}
 	}
 
+	log.Infof("Cloud Costs enabled: %t", env.IsCloudCostEnabled())
 	if env.IsCloudCostEnabled() {
 		repo := cloudcost.NewMemoryRepository()
+		keys, _ := repo.Keys()
+		log.Infof("repo: %v", keys)
 		a.CloudCostPipelineService = cloudcost.NewPipelineService(repo, a.CloudConfigController, cloudcost.DefaultIngestorConfiguration())
 		repoQuerier := cloudcost.NewRepositoryQuerier(repo)
 		a.CloudCostQueryService = cloudcost.NewQueryService(repoQuerier, repoQuerier)
@@ -50,9 +58,12 @@ func Execute(opts *CostModelOpts) error {
 
 	rootMux := http.NewServeMux()
 	a.Router.GET("/healthz", Healthz)
-	a.Router.GET("/allocation", a.ComputeAllocationHandler)
-	a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
-	a.Router.GET("/assets", a.ComputeAssetsHandler)
+
+	if env.IsKubernetesEnabled() {
+		a.Router.GET("/allocation", a.ComputeAllocationHandler)
+		a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
+		a.Router.GET("/assets", a.ComputeAssetsHandler)
+	}
 
 	a.Router.GET("/cloudCost", a.CloudCostQueryService.GetCloudCostHandler())
 	a.Router.GET("/cloudCost/view/graph", a.CloudCostQueryService.GetCloudCostViewGraphHandler())

+ 43 - 0
pkg/costmodel/router.go

@@ -1493,6 +1493,8 @@ func handlePanic(p errors.Panic) bool {
 func Initialize(additionalConfigWatchers ...*watcher.ConfigMapWatcher) *Accesses {
 	configWatchers := watcher.NewConfigMapWatchers(additionalConfigWatchers...)
 
+	log.Infof("+++Initialize: %v", configWatchers.GetWatchedConfigs())
+
 	var err error
 	if errorReportingEnabled {
 		err = sentry.Init(sentry.ClientOptions{Release: version.FriendlyVersion()})
@@ -1828,6 +1830,47 @@ func Initialize(additionalConfigWatchers ...*watcher.ConfigMapWatcher) *Accesses
 	return a
 }
 
+func InitializeWithoutKubernetes(additionalConfigWatchers ...*watcher.ConfigMapWatcher) *Accesses {
+	configWatchers := watcher.NewConfigMapWatchers(additionalConfigWatchers...)
+
+	log.Infof("+++InitializeWithoutKubernetes: %v", configWatchers.GetWatchedConfigs())
+
+	var err error
+	if errorReportingEnabled {
+		err = sentry.Init(sentry.ClientOptions{Release: version.FriendlyVersion()})
+		if err != nil {
+			log.Infof("Failed to initialize sentry for error reporting")
+		} else {
+			err = errors.SetPanicHandler(handlePanic)
+			if err != nil {
+				log.Infof("Failed to set panic handler: %s", err)
+			}
+		}
+	}
+
+	// // Create ConfigFileManager for synchronization of shared configuration
+	// confManager := config.NewConfigFileManager(&config.ConfigFileManagerOpts{
+	// 	BucketStoreConfig: env.GetKubecostConfigBucket(),
+	// 	LocalConfigPath:   "/",
+	// })
+
+	// configPrefix := env.GetConfigPathWithDefault("/var/configs/")
+
+	// cloudProviderKey := env.GetCloudProviderAPIKey()
+
+	a := &Accesses{
+		Router: httprouter.New(),
+	}
+	/*
+		a.Router.GET("/status", a.Status)
+		a.Router.GET("/logs/level", a.GetLogLevel)
+		a.Router.POST("/logs/level", a.SetLogLevel)
+
+		a.httpServices.RegisterAll(a.Router)
+	*/
+	return a
+}
+
 func writeErrorResponse(w http.ResponseWriter, code int, message string) {
 	out := map[string]string{
 		"message": message,

+ 10 - 0
pkg/env/costmodelenv.go

@@ -115,6 +115,8 @@ const (
 	DataRetentionDailyResolutionDaysEnvVar = "DATA_RETENTION_DAILY_RESOLUTION_DAYS"
 
 	CloudCostEnabledEnvVar          = "CLOUD_COST_ENABLED"
+	KubernetesEnabledEnvVar         = "KUBERNETES_ENABLED"
+	CloudIntegrationSecretPath      = "CLOUD_INTEGRATION_SECRET_PATH"
 	CloudCostMonthToDateIntervalVar = "CLOUD_COST_MONTH_TO_DATE_INTERVAL"
 	CloudCostRefreshRateHoursEnvVar = "CLOUD_COST_REFRESH_RATE_HOURS"
 	CloudCostQueryWindowDaysEnvVar  = "CLOUD_COST_QUERY_WINDOW_DAYS"
@@ -639,6 +641,14 @@ func IsCloudCostEnabled() bool {
 	return GetBool(CloudCostEnabledEnvVar, false)
 }
 
+func IsKubernetesEnabled() bool {
+	return GetBool(KubernetesEnabledEnvVar, true)
+}
+
+func GetCloudIntegrationSecretPath() string {
+	return Get(CloudIntegrationSecretPath, "cloud-integration.json")
+}
+
 func GetCloudCostMonthToDateInterval() int {
 	return GetInt(CloudCostMonthToDateIntervalVar, 6)
 }

+ 38 - 0
pkg/env/costmodelenv_test.go

@@ -123,3 +123,41 @@ func TestGetExportCSVMaxDays(t *testing.T) {
 		})
 	}
 }
+
+func TestGetKubernetesEnabled(t *testing.T) {
+	tests := []struct {
+		name string
+		want bool
+		pre  func()
+	}{
+		{
+			name: "Ensure the default value is true",
+			want: true,
+		},
+		{
+			name: "Ensure the value is true when KUBERNETES_ENABLED is set to true",
+			want: true,
+			pre: func() {
+				os.Setenv("EXPORT_KUBERNETES_ENABLED", "true")
+			},
+		},
+		{
+			name: "Ensure the value is false when KUBERNETES_ENABLED is set to false",
+			want: false,
+			pre: func() {
+				os.Setenv("EXPORT_KUBERNETES_ENABLED", "false")
+			},
+		},
+	}
+	for _, tt := range tests {
+		if tt.pre != nil {
+			tt.pre()
+		}
+		t.Run(tt.name, func(t *testing.T) {
+			if got := IsKubernetesEnabled(); got != tt.want {
+				t.Errorf("IsKubernetesEnabled() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+
+}