clustermap.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/opencost/opencost/modules/prometheus-source/pkg/env"
  9. "github.com/opencost/opencost/core/pkg/clusters"
  10. "github.com/opencost/opencost/core/pkg/log"
  11. "github.com/opencost/opencost/core/pkg/source"
  12. "github.com/opencost/opencost/core/pkg/util/retry"
  13. )
  14. const (
  15. LoadRetries int = 6
  16. LoadRetryDelay time.Duration = 10 * time.Second
  17. )
  18. // ClusterMap keeps records of all known cost-model clusters.
  19. type PrometheusClusterMap struct {
  20. lock sync.RWMutex
  21. contextFactory *ContextFactory
  22. clusters map[string]*clusters.ClusterInfo
  23. clusterInfo clusters.ClusterInfoProvider
  24. stop chan struct{}
  25. }
  26. // newPrometheusClusterMap creates a new ClusterMap implementation using prometheus
  27. func newPrometheusClusterMap(contextFactory *ContextFactory, cip clusters.ClusterInfoProvider, refresh time.Duration) clusters.ClusterMap {
  28. stop := make(chan struct{})
  29. cm := &PrometheusClusterMap{
  30. contextFactory: contextFactory,
  31. clusters: make(map[string]*clusters.ClusterInfo),
  32. clusterInfo: cip,
  33. stop: stop,
  34. }
  35. // Run an updater to ensure cluster data stays relevant over time
  36. go func() {
  37. // Immediately Attempt to refresh the clusters
  38. cm.refreshClusters()
  39. // Tick on interval and refresh clusters
  40. ticker := time.NewTicker(refresh)
  41. defer ticker.Stop()
  42. for {
  43. select {
  44. case <-ticker.C:
  45. cm.refreshClusters()
  46. case <-cm.stop:
  47. log.Infof("ClusterMap refresh stopped.")
  48. return
  49. }
  50. }
  51. }()
  52. return cm
  53. }
  54. // clusterInfoQuery returns the query string to load cluster info
  55. func clusterInfoQuery(offset string) string {
  56. return fmt.Sprintf("kubecost_cluster_info{%s}%s", env.GetPromClusterFilter(), offset)
  57. }
  58. // loadClusters loads all the cluster info to map
  59. func (pcm *PrometheusClusterMap) loadClusters() (map[string]*clusters.ClusterInfo, error) {
  60. var offset string = ""
  61. // Execute Query
  62. tryQuery := func() (interface{}, error) {
  63. ctx := pcm.contextFactory.NewNamedContext(ClusterMapContextName)
  64. resCh := ctx.QueryAtTime(clusterInfoQuery(offset), time.Now())
  65. r, e := resCh.Await()
  66. return r, e
  67. }
  68. // Retry on failure
  69. result, err := retry.Retry(context.Background(), tryQuery, uint(LoadRetries), LoadRetryDelay)
  70. qr, ok := result.([]*source.QueryResult)
  71. if !ok || err != nil {
  72. return nil, err
  73. }
  74. allClusters := make(map[string]*clusters.ClusterInfo)
  75. // Load the query results. Critical fields are id and name.
  76. for _, result := range qr {
  77. id, err := result.GetString("id")
  78. if err != nil {
  79. log.Warnf("Failed to load 'id' field for ClusterInfo")
  80. continue
  81. }
  82. name, err := result.GetString("name")
  83. if err != nil {
  84. log.Warnf("Failed to load 'name' field for ClusterInfo")
  85. continue
  86. }
  87. profile, err := result.GetString("clusterprofile")
  88. if err != nil {
  89. profile = ""
  90. }
  91. provider, err := result.GetString("provider")
  92. if err != nil {
  93. provider = ""
  94. }
  95. account, err := result.GetString("account")
  96. if err != nil {
  97. account = ""
  98. }
  99. project, err := result.GetString("project")
  100. if err != nil {
  101. project = ""
  102. }
  103. region, err := result.GetString("region")
  104. if err != nil {
  105. region = ""
  106. }
  107. provisioner, err := result.GetString("provisioner")
  108. if err != nil {
  109. provisioner = ""
  110. }
  111. allClusters[id] = &clusters.ClusterInfo{
  112. ID: id,
  113. Name: name,
  114. Profile: profile,
  115. Provider: provider,
  116. Account: account,
  117. Project: project,
  118. Region: region,
  119. Provisioner: provisioner,
  120. }
  121. }
  122. // populate the local cluster if it doesn't exist
  123. localInfo, err := pcm.getLocalClusterInfo()
  124. if err != nil {
  125. return allClusters, nil
  126. }
  127. // Check to see if the local cluster's id is part of our loaded clusters, and include if not
  128. if _, ok := allClusters[localInfo.ID]; !ok {
  129. allClusters[localInfo.ID] = localInfo
  130. }
  131. return allClusters, nil
  132. }
  133. // getLocalClusterInfo returns the local cluster info in the event there does not exist a metric available.
  134. func (pcm *PrometheusClusterMap) getLocalClusterInfo() (*clusters.ClusterInfo, error) {
  135. info := pcm.clusterInfo.GetClusterInfo()
  136. clusterInfo, err := clusters.MapToClusterInfo(info)
  137. if err != nil {
  138. return nil, fmt.Errorf("parsing local cluster info failed: %w", err)
  139. }
  140. return clusterInfo, nil
  141. }
  142. // refreshClusters loads the clusters and updates the internal map
  143. func (pcm *PrometheusClusterMap) refreshClusters() {
  144. updated, err := pcm.loadClusters()
  145. if err != nil {
  146. log.Errorf("Failed to load cluster info via query after %d retries", LoadRetries)
  147. return
  148. }
  149. pcm.lock.Lock()
  150. pcm.clusters = updated
  151. pcm.lock.Unlock()
  152. }
  153. // GetClusterIDs returns a slice containing all of the cluster identifiers.
  154. func (pcm *PrometheusClusterMap) GetClusterIDs() []string {
  155. pcm.lock.RLock()
  156. defer pcm.lock.RUnlock()
  157. var clusterIDs []string
  158. for id := range pcm.clusters {
  159. clusterIDs = append(clusterIDs, id)
  160. }
  161. return clusterIDs
  162. }
  163. // AsMap returns the cluster map as a standard go map
  164. func (pcm *PrometheusClusterMap) AsMap() map[string]*clusters.ClusterInfo {
  165. pcm.lock.RLock()
  166. defer pcm.lock.RUnlock()
  167. m := make(map[string]*clusters.ClusterInfo)
  168. for k, v := range pcm.clusters {
  169. m[k] = v.Clone()
  170. }
  171. return m
  172. }
  173. // InfoFor returns the ClusterInfo entry for the provided clusterID or nil if it
  174. // doesn't exist
  175. func (pcm *PrometheusClusterMap) InfoFor(clusterID string) *clusters.ClusterInfo {
  176. pcm.lock.RLock()
  177. defer pcm.lock.RUnlock()
  178. if info, ok := pcm.clusters[clusterID]; ok {
  179. return info.Clone()
  180. }
  181. return nil
  182. }
  183. // NameFor returns the name of the cluster provided the clusterID.
  184. func (pcm *PrometheusClusterMap) NameFor(clusterID string) string {
  185. pcm.lock.RLock()
  186. defer pcm.lock.RUnlock()
  187. if info, ok := pcm.clusters[clusterID]; ok {
  188. return info.Name
  189. }
  190. return ""
  191. }
  192. // NameIDFor returns an identifier in the format "<clusterName>/<clusterID>" if the cluster has an
  193. // assigned name. Otherwise, just the clusterID is returned.
  194. func (pcm *PrometheusClusterMap) NameIDFor(clusterID string) string {
  195. pcm.lock.RLock()
  196. defer pcm.lock.RUnlock()
  197. if info, ok := pcm.clusters[clusterID]; ok {
  198. if info.Name == "" {
  199. return clusterID
  200. }
  201. return fmt.Sprintf("%s/%s", info.Name, clusterID)
  202. }
  203. return clusterID
  204. }
  205. // SplitNameID is a helper method that removes the common split format and returns
  206. func SplitNameID(nameID string) (id string, name string) {
  207. if !strings.Contains(nameID, "/") {
  208. id = nameID
  209. name = ""
  210. return
  211. }
  212. split := strings.Split(nameID, "/")
  213. name = split[0]
  214. id = split[1]
  215. return
  216. }
  217. // StopRefresh stops the automatic internal map refresh
  218. func (pcm *PrometheusClusterMap) StopRefresh() {
  219. if pcm.stop != nil {
  220. close(pcm.stop)
  221. pcm.stop = nil
  222. }
  223. }