agent.go 7.7 KB

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