clustermap.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package collector
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/core/pkg/clusters"
  5. "github.com/opencost/opencost/core/pkg/log"
  6. )
  7. type collectorClusterMap struct {
  8. clusterInfo clusters.ClusterInfoProvider
  9. }
  10. func newCollectorClusterMap(clusterInfo clusters.ClusterInfoProvider) *collectorClusterMap {
  11. return &collectorClusterMap{
  12. clusterInfo: clusterInfo,
  13. }
  14. }
  15. // getLocalClusterInfo returns the local cluster info in the event there does not exist a metric available.
  16. func (c *collectorClusterMap) getLocalClusterInfo() (*clusters.ClusterInfo, error) {
  17. info := c.clusterInfo.GetClusterInfo()
  18. clusterInfo, err := clusters.MapToClusterInfo(info)
  19. if err != nil {
  20. return nil, fmt.Errorf("parsing local cluster info failed: %w", err)
  21. }
  22. return clusterInfo, nil
  23. }
  24. func (c *collectorClusterMap) GetClusterIDs() []string {
  25. info, err := c.getLocalClusterInfo()
  26. if err != nil {
  27. log.Errorf("%s", err.Error())
  28. return nil
  29. }
  30. return []string{info.ID}
  31. }
  32. func (c *collectorClusterMap) AsMap() map[string]*clusters.ClusterInfo {
  33. info, err := c.getLocalClusterInfo()
  34. if err != nil {
  35. log.Errorf("%s", err.Error())
  36. return nil
  37. }
  38. return map[string]*clusters.ClusterInfo{
  39. info.ID: info,
  40. }
  41. }
  42. func (c *collectorClusterMap) InfoFor(clusterID string) *clusters.ClusterInfo {
  43. info, err := c.getLocalClusterInfo()
  44. if err != nil {
  45. log.Errorf("%s", err.Error())
  46. return nil
  47. }
  48. if info.ID == clusterID {
  49. return info
  50. }
  51. return nil
  52. }
  53. func (c *collectorClusterMap) NameFor(clusterID string) string {
  54. info, err := c.getLocalClusterInfo()
  55. if err != nil {
  56. log.Errorf("%s", err.Error())
  57. return ""
  58. }
  59. if info.ID == clusterID {
  60. return info.Name
  61. }
  62. return ""
  63. }
  64. func (c *collectorClusterMap) NameIDFor(clusterID string) string {
  65. info, err := c.getLocalClusterInfo()
  66. if err != nil {
  67. log.Errorf("%s", err.Error())
  68. return clusterID
  69. }
  70. if info.ID == clusterID {
  71. return fmt.Sprintf("%s/%s", info.Name, clusterID)
  72. }
  73. return clusterID
  74. }