2
0

clustermap.go 6.6 KB

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