providerconfig.go 8.0 KB

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