agent.go 8.2 KB

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