providerconfig.go 8.0 KB

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