agent.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package agent
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/kubecost/cost-model/pkg/cloud"
  8. "github.com/kubecost/cost-model/pkg/clustercache"
  9. "github.com/kubecost/cost-model/pkg/config"
  10. "github.com/kubecost/cost-model/pkg/costmodel"
  11. "github.com/kubecost/cost-model/pkg/costmodel/clusters"
  12. "github.com/kubecost/cost-model/pkg/env"
  13. "github.com/kubecost/cost-model/pkg/kubeconfig"
  14. "github.com/kubecost/cost-model/pkg/log"
  15. "github.com/kubecost/cost-model/pkg/metrics"
  16. "github.com/kubecost/cost-model/pkg/prom"
  17. "github.com/kubecost/cost-model/pkg/util/watcher"
  18. prometheus "github.com/prometheus/client_golang/api"
  19. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  20. "github.com/prometheus/client_golang/prometheus/promhttp"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "github.com/rs/cors"
  23. "k8s.io/client-go/kubernetes"
  24. )
  25. // AgentOpts contain configuration options that can be passed to the Execute() method
  26. type AgentOpts struct {
  27. // Stubbed for future configuration
  28. }
  29. // ClusterExportInterval is the interval used to export the cluster if env.IsExportClusterCacheEnabled() is true
  30. const ClusterExportInterval = 5 * time.Minute
  31. // clusterExporter is used if env.IsExportClusterCacheEnabled() is set to true
  32. // it will export the kubernetes cluster data to a file on a specific interval
  33. var clusterExporter *clustercache.ClusterExporter
  34. func Healthz(w http.ResponseWriter, _ *http.Request) {
  35. w.WriteHeader(200)
  36. w.Header().Set("Content-Length", "0")
  37. w.Header().Set("Content-Type", "text/plain")
  38. }
  39. // initializes the kubernetes client cache
  40. func newKubernetesClusterCache() (kubernetes.Interface, clustercache.ClusterCache, error) {
  41. var err error
  42. // Kubernetes API setup
  43. kubeClientset, err := kubeconfig.LoadKubeClient("")
  44. if err != nil {
  45. return nil, nil, err
  46. }
  47. // Create Kubernetes Cluster Cache + Watchers
  48. k8sCache := clustercache.NewKubernetesClusterCache(kubeClientset)
  49. k8sCache.Run()
  50. return kubeClientset, k8sCache, nil
  51. }
  52. func newPrometheusClient() (prometheus.Client, error) {
  53. address := env.GetPrometheusServerEndpoint()
  54. if address == "" {
  55. return nil, fmt.Errorf("No address for prometheus set in $%s. Aborting.", env.PrometheusServerEndpointEnvVar)
  56. }
  57. queryConcurrency := env.GetMaxQueryConcurrency()
  58. log.Infof("Prometheus Client Max Concurrency set to %d", queryConcurrency)
  59. timeout := 120 * time.Second
  60. keepAlive := 120 * time.Second
  61. tlsHandshakeTimeout := 10 * time.Second
  62. var rateLimitRetryOpts *prom.RateLimitRetryOpts = nil
  63. if env.IsPrometheusRetryOnRateLimitResponse() {
  64. rateLimitRetryOpts = &prom.RateLimitRetryOpts{
  65. MaxRetries: env.GetPrometheusRetryOnRateLimitMaxRetries(),
  66. DefaultRetryWait: env.GetPrometheusRetryOnRateLimitDefaultWait(),
  67. }
  68. }
  69. promCli, err := prom.NewPrometheusClient(address, &prom.PrometheusClientConfig{
  70. Timeout: timeout,
  71. KeepAlive: keepAlive,
  72. TLSHandshakeTimeout: tlsHandshakeTimeout,
  73. TLSInsecureSkipVerify: env.GetInsecureSkipVerify(),
  74. RateLimitRetryOpts: rateLimitRetryOpts,
  75. Auth: &prom.ClientAuth{
  76. Username: env.GetDBBasicAuthUsername(),
  77. Password: env.GetDBBasicAuthUserPassword(),
  78. BearerToken: env.GetDBBearerToken(),
  79. },
  80. QueryConcurrency: queryConcurrency,
  81. QueryLogFile: "",
  82. })
  83. if err != nil {
  84. return nil, fmt.Errorf("Failed to create prometheus client, Error: %v", err)
  85. }
  86. m, err := prom.Validate(promCli)
  87. if err != nil || !m.Running {
  88. if err != nil {
  89. log.Errorf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prom.PrometheusTroubleshootingURL)
  90. } else if !m.Running {
  91. log.Errorf("Prometheus at %s is not running. Troubleshooting help available at: %s", address, prom.PrometheusTroubleshootingURL)
  92. }
  93. } else {
  94. log.Infof("Success: retrieved the 'up' query against prometheus at: %s", address)
  95. }
  96. api := prometheusAPI.NewAPI(promCli)
  97. _, err = api.Config(context.Background())
  98. if err != nil {
  99. log.Infof("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s. Ignore if using cortex/thanos here.", address, err.Error(), prom.PrometheusTroubleshootingURL)
  100. } else {
  101. log.Infof("Retrieved a prometheus config file from: %s", address)
  102. }
  103. return promCli, nil
  104. }
  105. func Execute(opts *AgentOpts) error {
  106. log.Infof("Starting Kubecost Agent")
  107. configWatchers := watcher.NewConfigMapWatchers()
  108. scrapeInterval := time.Minute
  109. promCli, err := newPrometheusClient()
  110. if err != nil {
  111. panic(err.Error())
  112. }
  113. // Lookup scrape interval for kubecost job, update if found
  114. si, err := prom.ScrapeIntervalFor(promCli, env.GetKubecostJobName())
  115. if err == nil {
  116. scrapeInterval = si
  117. }
  118. log.Infof("Using scrape interval of %f", scrapeInterval.Seconds())
  119. // initialize kubernetes client and cluster cache
  120. k8sClient, clusterCache, err := newKubernetesClusterCache()
  121. if err != nil {
  122. panic(err.Error())
  123. }
  124. // Create ConfigFileManager for synchronization of shared configuration
  125. confManager := config.NewConfigFileManager(&config.ConfigFileManagerOpts{
  126. BucketStoreConfig: env.GetKubecostConfigBucket(),
  127. LocalConfigPath: "/",
  128. })
  129. cloudProviderKey := env.GetCloudProviderAPIKey()
  130. cloudProvider, err := cloud.NewProvider(clusterCache, cloudProviderKey, confManager)
  131. if err != nil {
  132. panic(err.Error())
  133. }
  134. // Append the pricing config watcher
  135. configWatchers.AddWatcher(cloud.ConfigWatcherFor(cloudProvider))
  136. watchConfigFunc := configWatchers.ToWatchFunc()
  137. watchedConfigs := configWatchers.GetWatchedConfigs()
  138. kubecostNamespace := env.GetKubecostNamespace()
  139. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  140. for _, cw := range watchedConfigs {
  141. configs, err := k8sClient.CoreV1().ConfigMaps(kubecostNamespace).Get(context.Background(), cw, metav1.GetOptions{})
  142. if err != nil {
  143. log.Infof("No %s configmap found at install time, using existing configs: %s", cw, err.Error())
  144. } else {
  145. watchConfigFunc(configs)
  146. }
  147. }
  148. clusterCache.SetConfigMapUpdateFunc(watchConfigFunc)
  149. // Initialize cluster exporting if it's enabled
  150. if env.IsExportClusterCacheEnabled() {
  151. cacheLocation := confManager.ConfigFileAt("/var/configs/cluster-cache.json")
  152. clusterExporter = clustercache.NewClusterExporter(clusterCache, cacheLocation, ClusterExportInterval)
  153. clusterExporter.Run()
  154. }
  155. // ClusterInfo Provider to provide the cluster map with local and remote cluster data
  156. localClusterInfo := costmodel.NewLocalClusterInfoProvider(k8sClient, cloudProvider)
  157. var clusterInfoProvider clusters.ClusterInfoProvider
  158. if env.IsExportClusterInfoEnabled() {
  159. clusterInfoConf := confManager.ConfigFileAt("/var/configs/cluster-info.json")
  160. clusterInfoProvider = costmodel.NewClusterInfoWriteOnRequest(localClusterInfo, clusterInfoConf)
  161. } else {
  162. clusterInfoProvider = localClusterInfo
  163. }
  164. // Initialize ClusterMap for maintaining ClusterInfo by ClusterID
  165. clusterMap := clusters.NewClusterMap(promCli, clusterInfoProvider, 5*time.Minute)
  166. costModel := costmodel.NewCostModel(promCli, cloudProvider, clusterCache, clusterMap, scrapeInterval)
  167. // initialize Kubernetes Metrics Emitter
  168. metricsEmitter := costmodel.NewCostModelMetricsEmitter(promCli, clusterCache, cloudProvider, clusterInfoProvider, costModel)
  169. // download pricing data
  170. err = cloudProvider.DownloadPricingData()
  171. if err != nil {
  172. log.Errorf("Error downloading pricing data: %s", err)
  173. }
  174. // start emitting metrics
  175. metricsEmitter.Start()
  176. rootMux := http.NewServeMux()
  177. rootMux.HandleFunc("/healthz", Healthz)
  178. rootMux.Handle("/metrics", promhttp.Handler())
  179. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  180. handler := cors.AllowAll().Handler(telemetryHandler)
  181. return http.ListenAndServe(fmt.Sprintf(":%d", env.GetKubecostMetricsPort()), handler)
  182. }