agent.go 7.5 KB

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