clustermanager.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package clusters
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "io/ioutil"
  6. "strings"
  7. "github.com/google/uuid"
  8. "github.com/opencost/opencost/pkg/log"
  9. "github.com/opencost/opencost/pkg/util/fileutil"
  10. "github.com/opencost/opencost/pkg/util/json"
  11. "sigs.k8s.io/yaml"
  12. )
  13. // The details key used to provide auth information
  14. const DetailsAuthKey = "auth"
  15. // Authentication Information
  16. type ClusterConfigEntryAuth struct {
  17. // The type of authentication provider to use
  18. Type string `yaml:"type"`
  19. // Data expressed as a secret
  20. SecretName string `yaml:"secretName,omitempty"`
  21. // Any data specifically needed by the auth provider
  22. Data string `yaml:"data,omitempty"`
  23. // User and Password as a possible input
  24. User string `yaml:"user,omitempty"`
  25. Pass string `yaml:"pass,omitempty"`
  26. }
  27. // Cluster definition from a configuration yaml
  28. type ClusterConfigEntry struct {
  29. Name string `yaml:"name"`
  30. Address string `yaml:"address"`
  31. Auth *ClusterConfigEntryAuth `yaml:"auth,omitempty"`
  32. Details map[string]interface{} `yaml:"details,omitempty"`
  33. }
  34. // ClusterDefinition
  35. type ClusterDefinition struct {
  36. ID string `json:"id,omitempty"`
  37. Name string `json:"name"`
  38. Address string `json:"address"`
  39. Details map[string]interface{} `json:"details,omitempty"`
  40. }
  41. // ClusterStorage interface defines an implementation prototype for a storage responsible
  42. // for ClusterDefinition instances
  43. type ClusterStorage interface {
  44. // Add only if the key does not exist
  45. AddIfNotExists(key string, cluster []byte) error
  46. // Adds the encoded cluster to storage if it doesn't exist. Otherwise, update the existing
  47. // value with the provided.
  48. AddOrUpdate(key string, cluster []byte) error
  49. // Removes a key from the cluster storage
  50. Remove(key string) error
  51. // Iterates through all key/values for the storage and calls the handler func. If a handler returns
  52. // an error, the iteration stops.
  53. Each(handler func(string, []byte) error) error
  54. // Closes the backing storage
  55. Close() error
  56. }
  57. // ClusterManager provides an implementation
  58. type ClusterManager struct {
  59. storage ClusterStorage
  60. // cache map[string]*ClusterDefinition
  61. }
  62. // Creates a new ClusterManager instance using the provided storage
  63. func NewClusterManager(storage ClusterStorage) *ClusterManager {
  64. return &ClusterManager{
  65. storage: storage,
  66. }
  67. }
  68. // Creates a new ClusterManager instance using the provided storage and populates a
  69. // yaml configured list of clusters
  70. func NewConfiguredClusterManager(storage ClusterStorage, config string) *ClusterManager {
  71. clusterManager := NewClusterManager(storage)
  72. exists, err := fileutil.FileExists(config)
  73. if !exists {
  74. if err != nil {
  75. log.Errorf("Failed to load config file: %s. Error: %s", config, err.Error())
  76. }
  77. return clusterManager
  78. }
  79. data, err := ioutil.ReadFile(config)
  80. if err != nil {
  81. return clusterManager
  82. }
  83. var entries []*ClusterConfigEntry
  84. err = yaml.Unmarshal(data, &entries)
  85. if err != nil {
  86. return clusterManager
  87. }
  88. for _, entry := range entries {
  89. details := entry.Details
  90. if details == nil {
  91. details = make(map[string]interface{})
  92. }
  93. if entry.Auth != nil {
  94. authData, err := getAuth(entry.Auth)
  95. if err != nil {
  96. log.Errorf("%s", err)
  97. } else {
  98. details[DetailsAuthKey] = authData
  99. }
  100. }
  101. clusterManager.Add(ClusterDefinition{
  102. ID: entry.Name,
  103. Name: entry.Name,
  104. Address: entry.Address,
  105. Details: details,
  106. })
  107. }
  108. return clusterManager
  109. }
  110. // Add Adds a cluster definition, but will not update an existing entry.
  111. func (cm *ClusterManager) Add(cluster ClusterDefinition) (*ClusterDefinition, error) {
  112. // First time add
  113. if cluster.ID == "" {
  114. cluster.ID = uuid.New().String()
  115. }
  116. data, err := json.Marshal(cluster)
  117. if err != nil {
  118. return nil, err
  119. }
  120. err = cm.storage.AddIfNotExists(cluster.ID, data)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return &cluster, nil
  125. }
  126. // AddOrUpdate will add the cluster definition if it doesn't exist, or update the existing definition
  127. // if it does exist.
  128. func (cm *ClusterManager) AddOrUpdate(cluster ClusterDefinition) (*ClusterDefinition, error) {
  129. // First time add
  130. if cluster.ID == "" {
  131. cluster.ID = uuid.New().String()
  132. }
  133. data, err := json.Marshal(cluster)
  134. if err != nil {
  135. return nil, err
  136. }
  137. err = cm.storage.AddOrUpdate(cluster.ID, data)
  138. if err != nil {
  139. return nil, err
  140. }
  141. return &cluster, nil
  142. }
  143. // Remove will remove a cluster definition by id.
  144. func (cm *ClusterManager) Remove(id string) error {
  145. return cm.storage.Remove(id)
  146. }
  147. // GetAll will return all of the cluster definitions
  148. func (cm *ClusterManager) GetAll() []*ClusterDefinition {
  149. clusters := []*ClusterDefinition{}
  150. err := cm.storage.Each(func(key string, cluster []byte) error {
  151. var cd ClusterDefinition
  152. err := json.Unmarshal(cluster, &cd)
  153. if err != nil {
  154. log.Errorf("Failed to unmarshal json cluster definition for key: %s", key)
  155. return nil
  156. }
  157. clusters = append(clusters, &cd)
  158. return nil
  159. })
  160. if err != nil {
  161. log.Infof("[Error] Failed to load list of clusters: %s", err.Error())
  162. }
  163. return clusters
  164. }
  165. // Close will close the backing database
  166. func (cm *ClusterManager) Close() error {
  167. return cm.storage.Close()
  168. }
  169. func toBasicAuth(user, pass string) string {
  170. return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass)))
  171. }
  172. func fileFromSecret(secretName string) string {
  173. return fmt.Sprintf("/var/secrets/%s/auth", secretName)
  174. }
  175. func fromSecret(secretName string) (string, error) {
  176. file := fileFromSecret(secretName)
  177. exists, err := fileutil.FileExists(file)
  178. if !exists || err != nil {
  179. return "", fmt.Errorf("Failed to locate secret: %s", file)
  180. }
  181. data, err := ioutil.ReadFile(file)
  182. if err != nil {
  183. return "", fmt.Errorf("Failed to load secret: %s", file)
  184. }
  185. return base64.StdEncoding.EncodeToString(data), nil
  186. }
  187. func getAuth(auth *ClusterConfigEntryAuth) (string, error) {
  188. // We only support basic auth currently
  189. if !strings.EqualFold(auth.Type, "basic") {
  190. return "", fmt.Errorf("Authentication Type: '%s' is not supported", auth.Type)
  191. }
  192. if auth.SecretName != "" {
  193. return fromSecret(auth.SecretName)
  194. }
  195. if auth.Data != "" {
  196. return auth.Data, nil
  197. }
  198. if auth.User != "" && auth.Pass != "" {
  199. return toBasicAuth(auth.User, auth.Pass), nil
  200. }
  201. return "", fmt.Errorf("No valid basic auth parameters provided.")
  202. }