providerconfig.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package cloud
  2. import (
  3. "fmt"
  4. gopath "path"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "github.com/kubecost/cost-model/pkg/config"
  10. "github.com/kubecost/cost-model/pkg/env"
  11. "github.com/kubecost/cost-model/pkg/log"
  12. "github.com/kubecost/cost-model/pkg/util/json"
  13. "github.com/microcosm-cc/bluemonday"
  14. "k8s.io/klog"
  15. )
  16. var sanitizePolicy = bluemonday.UGCPolicy()
  17. // ProviderConfig is a utility class that provides a thread-safe configuration storage/cache for all Provider
  18. // implementations
  19. type ProviderConfig struct {
  20. lock *sync.Mutex
  21. configManager *config.ConfigFileManager
  22. configFile *config.ConfigFile
  23. customPricing *CustomPricing
  24. watcherHandleID config.HandlerID
  25. }
  26. // NewProviderConfig creates a new ConfigFile and returns the ProviderConfig
  27. func NewProviderConfig(configManager *config.ConfigFileManager, fileName string) *ProviderConfig {
  28. configFile := configManager.ConfigFileAt(configPathFor(fileName))
  29. pc := &ProviderConfig{
  30. lock: new(sync.Mutex),
  31. configManager: configManager,
  32. configFile: configFile,
  33. customPricing: nil,
  34. }
  35. // add the provider config func as handler for the config file changes
  36. pc.watcherHandleID = configFile.AddChangeHandler(pc.onConfigFileUpdated)
  37. return pc
  38. }
  39. // onConfigFileUpdated handles any time the config file contents are updated, created, or deleted
  40. func (pc *ProviderConfig) onConfigFileUpdated(changeType config.ChangeType, data []byte) {
  41. // TODO: (bolt) Currently this has the side-effect of setting pc.customPricing twice when the update
  42. // TODO: (bolt) is made from this ProviderConfig instance. We'll need to implement a way of identifying
  43. // TODO: (bolt) when to ignore updates when the change and handler are the same source
  44. log.Infof("CustomPricing Config Updated: %s", changeType)
  45. switch changeType {
  46. case config.ChangeTypeCreated:
  47. fallthrough
  48. case config.ChangeTypeModified:
  49. pc.lock.Lock()
  50. defer pc.lock.Unlock()
  51. customPricing := new(CustomPricing)
  52. err := json.Unmarshal(data, customPricing)
  53. if err != nil {
  54. klog.Infof("Could not decode Custom Pricing file at path %s. Using default.", pc.configFile.Path())
  55. customPricing = DefaultPricing()
  56. }
  57. pc.customPricing = customPricing
  58. if pc.customPricing.SpotGPU == "" {
  59. pc.customPricing.SpotGPU = DefaultPricing().SpotGPU // Migration for users without this value set by default.
  60. }
  61. if pc.customPricing.ShareTenancyCosts == "" {
  62. pc.customPricing.ShareTenancyCosts = defaultShareTenancyCost
  63. }
  64. }
  65. }
  66. // Non-ThreadSafe logic to load the config file if a cache does not exist. Flag to write
  67. // the default config if the config file doesn't exist.
  68. func (pc *ProviderConfig) loadConfig(writeIfNotExists bool) (*CustomPricing, error) {
  69. if pc.customPricing != nil {
  70. return pc.customPricing, nil
  71. }
  72. exists, err := pc.configFile.Exists()
  73. // File Error other than NotExists
  74. if err != nil {
  75. klog.Infof("Custom Pricing file at path '%s' read error: '%s'", pc.configFile.Path(), err.Error())
  76. return DefaultPricing(), err
  77. }
  78. // File Doesn't Exist
  79. if !exists {
  80. klog.Infof("Could not find Custom Pricing file at path '%s'", pc.configFile.Path())
  81. pc.customPricing = DefaultPricing()
  82. // Only write the file if flag enabled
  83. if writeIfNotExists {
  84. cj, err := json.Marshal(pc.customPricing)
  85. if err != nil {
  86. return pc.customPricing, err
  87. }
  88. err = pc.configFile.Write(cj)
  89. if err != nil {
  90. klog.Infof("Could not write Custom Pricing file to path '%s'", pc.configFile.Path())
  91. return pc.customPricing, err
  92. }
  93. }
  94. return pc.customPricing, nil
  95. }
  96. // File Exists - Read all contents of file, unmarshal json
  97. byteValue, err := pc.configFile.Read()
  98. if err != nil {
  99. klog.Infof("Could not read Custom Pricing file at path %s", pc.configFile.Path())
  100. // If read fails, we don't want to cache default, assuming that the file is valid
  101. return DefaultPricing(), err
  102. }
  103. var customPricing CustomPricing
  104. err = json.Unmarshal(byteValue, &customPricing)
  105. if err != nil {
  106. klog.Infof("Could not decode Custom Pricing file at path %s", pc.configFile.Path())
  107. return DefaultPricing(), err
  108. }
  109. pc.customPricing = &customPricing
  110. if pc.customPricing.SpotGPU == "" {
  111. pc.customPricing.SpotGPU = DefaultPricing().SpotGPU // Migration for users without this value set by default.
  112. }
  113. if pc.customPricing.ShareTenancyCosts == "" {
  114. pc.customPricing.ShareTenancyCosts = defaultShareTenancyCost
  115. }
  116. return pc.customPricing, nil
  117. }
  118. // ThreadSafe method for retrieving the custom pricing config.
  119. func (pc *ProviderConfig) GetCustomPricingData() (*CustomPricing, error) {
  120. pc.lock.Lock()
  121. defer pc.lock.Unlock()
  122. return pc.loadConfig(true)
  123. }
  124. // ConfigFileManager returns the ConfigFileManager instance used to manage the CustomPricing
  125. // configuration. In the event of a multi-provider setup, this instance should be used to
  126. // configure any other configuration providers.
  127. func (pc *ProviderConfig) ConfigFileManager() *config.ConfigFileManager {
  128. return pc.configManager
  129. }
  130. // Allows a call to manually update the configuration while maintaining proper thread-safety
  131. // for read/write methods.
  132. func (pc *ProviderConfig) Update(updateFunc func(*CustomPricing) error) (*CustomPricing, error) {
  133. pc.lock.Lock()
  134. defer pc.lock.Unlock()
  135. // Load Config, set flag to _not_ write if failure to find file.
  136. // We're about to write the updated values, so we don't want to double write.
  137. c, _ := pc.loadConfig(false)
  138. // Execute Update - On error, return the in-memory config but don't update cache
  139. // explicitly
  140. err := updateFunc(c)
  141. if err != nil {
  142. return c, err
  143. }
  144. // Cache Update (possible the ptr already references the cached value)
  145. pc.customPricing = c
  146. cj, err := json.Marshal(c)
  147. if err != nil {
  148. return c, err
  149. }
  150. err = pc.configFile.Write(cj)
  151. if err != nil {
  152. return c, err
  153. }
  154. return c, nil
  155. }
  156. // ThreadSafe update of the config using a string map
  157. func (pc *ProviderConfig) UpdateFromMap(a map[string]string) (*CustomPricing, error) {
  158. // Run our Update() method using SetCustomPricingField logic
  159. return pc.Update(func(c *CustomPricing) error {
  160. for k, v := range a {
  161. // Just so we consistently supply / receive the same values, uppercase the first letter.
  162. kUpper := strings.Title(k)
  163. if kUpper == "CPU" || kUpper == "SpotCPU" || kUpper == "RAM" || kUpper == "SpotRAM" || kUpper == "GPU" || kUpper == "Storage" {
  164. val, err := strconv.ParseFloat(v, 64)
  165. if err != nil {
  166. return fmt.Errorf("Unable to parse CPU from string to float: %s", err.Error())
  167. }
  168. v = fmt.Sprintf("%f", val/730)
  169. }
  170. err := SetCustomPricingField(c, kUpper, v)
  171. if err != nil {
  172. return err
  173. }
  174. }
  175. return nil
  176. })
  177. }
  178. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  179. func DefaultPricing() *CustomPricing {
  180. return &CustomPricing{
  181. Provider: "base",
  182. Description: "Default prices based on GCP us-central1",
  183. CPU: "0.031611",
  184. SpotCPU: "0.006655",
  185. RAM: "0.004237",
  186. SpotRAM: "0.000892",
  187. GPU: "0.95",
  188. SpotGPU: "0.308",
  189. Storage: "0.00005479452",
  190. ZoneNetworkEgress: "0.01",
  191. RegionNetworkEgress: "0.01",
  192. InternetNetworkEgress: "0.12",
  193. CustomPricesEnabled: "false",
  194. ShareTenancyCosts: "true",
  195. }
  196. }
  197. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  198. structValue := reflect.ValueOf(obj).Elem()
  199. structFieldValue := structValue.FieldByName(name)
  200. if !structFieldValue.IsValid() {
  201. return fmt.Errorf("No such field: %s in obj", name)
  202. }
  203. if !structFieldValue.CanSet() {
  204. return fmt.Errorf("Cannot set %s field value", name)
  205. }
  206. structFieldType := structFieldValue.Type()
  207. value = sanitizePolicy.Sanitize(value)
  208. val := reflect.ValueOf(value)
  209. if structFieldType != val.Type() {
  210. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  211. }
  212. structFieldValue.Set(val)
  213. return nil
  214. }
  215. // Returns the configuration directory concatenated with a specific config file name
  216. func configPathFor(filename string) string {
  217. path := env.GetConfigPathWithDefault("/models/")
  218. return gopath.Join(path, filename)
  219. }