agent.go 8.3 KB

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