agent.go 7.8 KB

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