agent.go 8.0 KB

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