clustermanager.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package clustermanager
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "strings"
  8. "github.com/google/uuid"
  9. "github.com/kubecost/cost-model/pkg/util"
  10. "k8s.io/klog"
  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. type ClusterManager struct {
  58. storage ClusterStorage
  59. // cache map[string]*ClusterDefinition
  60. }
  61. // Creates a new ClusterManager instance using the provided storage
  62. func NewClusterManager(storage ClusterStorage) *ClusterManager {
  63. return &ClusterManager{
  64. storage: storage,
  65. }
  66. }
  67. // Creates a new ClusterManager instance using the provided storage and populates a
  68. // yaml configured list of clusters
  69. func NewConfiguredClusterManager(storage ClusterStorage, config string) *ClusterManager {
  70. clusterManager := NewClusterManager(storage)
  71. exists, err := util.FileExists(config)
  72. if !exists {
  73. if err != nil {
  74. klog.V(1).Infof("[Error] Failed to load config file: %s. Error: %s", config, err.Error())
  75. }
  76. return clusterManager
  77. }
  78. data, err := ioutil.ReadFile(config)
  79. if err != nil {
  80. return clusterManager
  81. }
  82. var entries []*ClusterConfigEntry
  83. err = yaml.Unmarshal(data, &entries)
  84. if err != nil {
  85. return clusterManager
  86. }
  87. for _, entry := range entries {
  88. details := entry.Details
  89. if details == nil {
  90. details = make(map[string]interface{})
  91. }
  92. if entry.Auth != nil {
  93. authData, err := getAuth(entry.Auth)
  94. if err != nil {
  95. klog.V(1).Infof("[Error]: %s", err)
  96. } else {
  97. details[DetailsAuthKey] = authData
  98. }
  99. }
  100. clusterManager.Add(ClusterDefinition{
  101. ID: entry.Name,
  102. Name: entry.Name,
  103. Address: entry.Address,
  104. Details: details,
  105. })
  106. }
  107. return clusterManager
  108. }
  109. // Adds, but will not update an existing entry.
  110. func (cm *ClusterManager) Add(cluster ClusterDefinition) (*ClusterDefinition, error) {
  111. // First time add
  112. if cluster.ID == "" {
  113. cluster.ID = uuid.New().String()
  114. }
  115. data, err := json.Marshal(cluster)
  116. if err != nil {
  117. return nil, err
  118. }
  119. err = cm.storage.AddIfNotExists(cluster.ID, data)
  120. if err != nil {
  121. return nil, err
  122. }
  123. return &cluster, nil
  124. }
  125. func (cm *ClusterManager) AddOrUpdate(cluster ClusterDefinition) (*ClusterDefinition, error) {
  126. // First time add
  127. if cluster.ID == "" {
  128. cluster.ID = uuid.New().String()
  129. }
  130. data, err := json.Marshal(cluster)
  131. if err != nil {
  132. return nil, err
  133. }
  134. err = cm.storage.AddOrUpdate(cluster.ID, data)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return &cluster, nil
  139. }
  140. func (cm *ClusterManager) Remove(id string) error {
  141. return cm.storage.Remove(id)
  142. }
  143. func (cm *ClusterManager) GetAll() []*ClusterDefinition {
  144. clusters := []*ClusterDefinition{}
  145. err := cm.storage.Each(func(key string, cluster []byte) error {
  146. var cd ClusterDefinition
  147. err := json.Unmarshal(cluster, &cd)
  148. if err != nil {
  149. klog.V(1).Infof("[Error] Failed to unmarshal json cluster definition for key: %s", key)
  150. return nil
  151. }
  152. clusters = append(clusters, &cd)
  153. return nil
  154. })
  155. if err != nil {
  156. klog.Infof("[Error] Failed to load list of clusters: %s", err.Error())
  157. }
  158. return clusters
  159. }
  160. func (cm *ClusterManager) Close() error {
  161. return cm.storage.Close()
  162. }
  163. func toBasicAuth(user, pass string) string {
  164. return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass)))
  165. }
  166. func fileFromSecret(secretName string) string {
  167. return fmt.Sprintf("/var/secrets/%s/auth", secretName)
  168. }
  169. func fromSecret(secretName string) (string, error) {
  170. file := fileFromSecret(secretName)
  171. exists, err := util.FileExists(file)
  172. if !exists || err != nil {
  173. return "", fmt.Errorf("Failed to locate secret: %s", file)
  174. }
  175. data, err := ioutil.ReadFile(file)
  176. if err != nil {
  177. return "", fmt.Errorf("Failed to load secret: %s", file)
  178. }
  179. return base64.StdEncoding.EncodeToString(data), nil
  180. }
  181. func getAuth(auth *ClusterConfigEntryAuth) (string, error) {
  182. // We only support basic auth currently
  183. if !strings.EqualFold(auth.Type, "basic") {
  184. return "", fmt.Errorf("Authentication Type: '%s' is not supported", auth.Type)
  185. }
  186. if auth.SecretName != "" {
  187. return fromSecret(auth.SecretName)
  188. }
  189. if auth.Data != "" {
  190. return auth.Data, nil
  191. }
  192. if auth.User != "" && auth.Pass != "" {
  193. return toBasicAuth(auth.User, auth.Pass), nil
  194. }
  195. return "", fmt.Errorf("No valid basic auth parameters provided.")
  196. }