agent.go 7.8 KB

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