providerconfig.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package cloud
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. gopath "path"
  7. "reflect"
  8. "strconv"
  9. "sync"
  10. "github.com/microcosm-cc/bluemonday"
  11. "github.com/opencost/opencost/pkg/config"
  12. "github.com/opencost/opencost/pkg/env"
  13. "github.com/opencost/opencost/pkg/log"
  14. "github.com/opencost/opencost/pkg/util/json"
  15. )
  16. const closedSourceConfigMount = "models/"
  17. var sanitizePolicy = bluemonday.UGCPolicy()
  18. // ProviderConfig is a utility class that provides a thread-safe configuration storage/cache for all Provider
  19. // implementations
  20. type ProviderConfig struct {
  21. lock *sync.Mutex
  22. configManager *config.ConfigFileManager
  23. configFile *config.ConfigFile
  24. customPricing *CustomPricing
  25. watcherHandleID config.HandlerID
  26. }
  27. // NewProviderConfig creates a new ConfigFile and returns the ProviderConfig
  28. func NewProviderConfig(configManager *config.ConfigFileManager, fileName string) *ProviderConfig {
  29. configFile := configManager.ConfigFileAt(configPathFor(fileName))
  30. pc := &ProviderConfig{
  31. lock: new(sync.Mutex),
  32. configManager: configManager,
  33. configFile: configFile,
  34. customPricing: nil,
  35. }
  36. // add the provider config func as handler for the config file changes
  37. pc.watcherHandleID = configFile.AddChangeHandler(pc.onConfigFileUpdated)
  38. return pc
  39. }
  40. // onConfigFileUpdated handles any time the config file contents are updated, created, or deleted
  41. func (pc *ProviderConfig) onConfigFileUpdated(changeType config.ChangeType, data []byte) {
  42. // TODO: (bolt) Currently this has the side-effect of setting pc.customPricing twice when the update
  43. // TODO: (bolt) is made from this ProviderConfig instance. We'll need to implement a way of identifying
  44. // TODO: (bolt) when to ignore updates when the change and handler are the same source
  45. log.Infof("CustomPricing Config Updated: %s", changeType)
  46. switch changeType {
  47. case config.ChangeTypeCreated:
  48. fallthrough
  49. case config.ChangeTypeModified:
  50. pc.lock.Lock()
  51. defer pc.lock.Unlock()
  52. customPricing := new(CustomPricing)
  53. err := json.Unmarshal(data, customPricing)
  54. if err != nil {
  55. log.Infof("Could not decode Custom Pricing file at path %s. Using default.", pc.configFile.Path())
  56. customPricing = DefaultPricing()
  57. }
  58. pc.customPricing = customPricing
  59. if pc.customPricing.SpotGPU == "" {
  60. pc.customPricing.SpotGPU = DefaultPricing().SpotGPU // Migration for users without this value set by default.
  61. }
  62. if pc.customPricing.ShareTenancyCosts == "" {
  63. pc.customPricing.ShareTenancyCosts = defaultShareTenancyCost
  64. }
  65. }
  66. }
  67. // Non-ThreadSafe logic to load the config file if a cache does not exist. Flag to write
  68. // the default config if the config file doesn't exist.
  69. func (pc *ProviderConfig) loadConfig(writeIfNotExists bool) (*CustomPricing, error) {
  70. if pc.customPricing != nil {
  71. return pc.customPricing, nil
  72. }
  73. exists, err := pc.configFile.Exists()
  74. // File Error other than NotExists
  75. if err != nil {
  76. log.Infof("Custom Pricing file at path '%s' read error: '%s'", pc.configFile.Path(), err.Error())
  77. return DefaultPricing(), err
  78. }
  79. // File Doesn't Exist
  80. if !exists {
  81. log.Infof("Could not find Custom Pricing file at path '%s'", pc.configFile.Path())
  82. pc.customPricing = DefaultPricing()
  83. // If config file is not present use the contents from mount models/ as pricing data
  84. // in closed source rather than from from DefaultPricing as first source of truth.
  85. // since most images will already have a mount, to avail this facility user needs to delete the
  86. // config file manually from configpath else default pricing still holds good.
  87. fileName := filenameInConfigPath(pc.configFile.Path())
  88. defaultPricing, err := ReturnPricingFromConfigs(fileName)
  89. if err == nil {
  90. pc.customPricing = defaultPricing
  91. }
  92. // Only write the file if flag enabled
  93. if writeIfNotExists {
  94. cj, err := json.Marshal(pc.customPricing)
  95. if err != nil {
  96. return pc.customPricing, err
  97. }
  98. err = pc.configFile.Write(cj)
  99. if err != nil {
  100. log.Infof("Could not write Custom Pricing file to path '%s'", pc.configFile.Path())
  101. return pc.customPricing, err
  102. }
  103. }
  104. return pc.customPricing, nil
  105. }
  106. // File Exists - Read all contents of file, unmarshal json
  107. byteValue, err := pc.configFile.Read()
  108. if err != nil {
  109. log.Infof("Could not read Custom Pricing file at path %s", pc.configFile.Path())
  110. // If read fails, we don't want to cache default, assuming that the file is valid
  111. return DefaultPricing(), err
  112. }
  113. var customPricing CustomPricing
  114. err = json.Unmarshal(byteValue, &customPricing)
  115. if err != nil {
  116. log.Infof("Could not decode Custom Pricing file at path %s", pc.configFile.Path())
  117. return DefaultPricing(), err
  118. }
  119. pc.customPricing = &customPricing
  120. if pc.customPricing.SpotGPU == "" {
  121. pc.customPricing.SpotGPU = DefaultPricing().SpotGPU // Migration for users without this value set by default.
  122. }
  123. if pc.customPricing.ShareTenancyCosts == "" {
  124. pc.customPricing.ShareTenancyCosts = defaultShareTenancyCost
  125. }
  126. return pc.customPricing, nil
  127. }
  128. // ThreadSafe method for retrieving the custom pricing config.
  129. func (pc *ProviderConfig) GetCustomPricingData() (*CustomPricing, error) {
  130. pc.lock.Lock()
  131. defer pc.lock.Unlock()
  132. return pc.loadConfig(true)
  133. }
  134. // ConfigFileManager returns the ConfigFileManager instance used to manage the CustomPricing
  135. // configuration. In the event of a multi-provider setup, this instance should be used to
  136. // configure any other configuration providers.
  137. func (pc *ProviderConfig) ConfigFileManager() *config.ConfigFileManager {
  138. return pc.configManager
  139. }
  140. // Allows a call to manually update the configuration while maintaining proper thread-safety
  141. // for read/write methods.
  142. func (pc *ProviderConfig) Update(updateFunc func(*CustomPricing) error) (*CustomPricing, error) {
  143. pc.lock.Lock()
  144. defer pc.lock.Unlock()
  145. // Load Config, set flag to _not_ write if failure to find file.
  146. // We're about to write the updated values, so we don't want to double write.
  147. c, _ := pc.loadConfig(false)
  148. // Execute Update - On error, return the in-memory config but don't update cache
  149. // explicitly
  150. err := updateFunc(c)
  151. if err != nil {
  152. return c, err
  153. }
  154. // Cache Update (possible the ptr already references the cached value)
  155. pc.customPricing = c
  156. cj, err := json.Marshal(c)
  157. if err != nil {
  158. return c, err
  159. }
  160. err = pc.configFile.Write(cj)
  161. if err != nil {
  162. return c, err
  163. }
  164. return c, nil
  165. }
  166. // ThreadSafe update of the config using a string map
  167. func (pc *ProviderConfig) UpdateFromMap(a map[string]string) (*CustomPricing, error) {
  168. // Run our Update() method using SetCustomPricingField logic
  169. return pc.Update(func(c *CustomPricing) error {
  170. for k, v := range a {
  171. // Just so we consistently supply / receive the same values, uppercase the first letter.
  172. kUpper := toTitle.String(k)
  173. if kUpper == "CPU" || kUpper == "SpotCPU" || kUpper == "RAM" || kUpper == "SpotRAM" || kUpper == "GPU" || kUpper == "Storage" {
  174. val, err := strconv.ParseFloat(v, 64)
  175. if err != nil {
  176. return fmt.Errorf("Unable to parse CPU from string to float: %s", err.Error())
  177. }
  178. v = fmt.Sprintf("%f", val/730)
  179. }
  180. err := SetCustomPricingField(c, kUpper, v)
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. return nil
  186. })
  187. }
  188. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  189. func DefaultPricing() *CustomPricing {
  190. // https://cloud.google.com/compute/all-pricing
  191. return &CustomPricing{
  192. Provider: "base",
  193. Description: "Default prices based on GCP us-central1",
  194. // E2 machine types in GCP us-central1 (Iowa)
  195. CPU: "0.021811", // per vCPU hour
  196. SpotCPU: "0.006543", // per vCPU hour
  197. RAM: "0.002923", // per G(i?)B hour
  198. SpotRAM: "0.000877", // per G(i?)B hour
  199. // There are many GPU types. This serves as a reasonably-appropriate
  200. // estimate within a broad range (0.35 up to 3.93)
  201. GPU: "0.95", // per GPU hour
  202. // Same story as above.
  203. SpotGPU: "0.308", // per GPU hour
  204. // This is the "Standard provision space" pricing in the "Disk pricing"
  205. // table.
  206. //
  207. // (($.04 / month) per G(i?)B) *
  208. // month/730 hours =
  209. // 0.00005479452054794521
  210. Storage: "0.00005479452",
  211. ZoneNetworkEgress: "0.01",
  212. RegionNetworkEgress: "0.01",
  213. InternetNetworkEgress: "0.12",
  214. CustomPricesEnabled: "false",
  215. ShareTenancyCosts: "true",
  216. }
  217. }
  218. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  219. structValue := reflect.ValueOf(obj).Elem()
  220. structFieldValue := structValue.FieldByName(name)
  221. if !structFieldValue.IsValid() {
  222. return fmt.Errorf("No such field: %s in obj", name)
  223. }
  224. if !structFieldValue.CanSet() {
  225. return fmt.Errorf("Cannot set %s field value", name)
  226. }
  227. structFieldType := structFieldValue.Type()
  228. value = sanitizePolicy.Sanitize(value)
  229. val := reflect.ValueOf(value)
  230. if structFieldType != val.Type() {
  231. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  232. }
  233. structFieldValue.Set(val)
  234. return nil
  235. }
  236. // Returns the configuration directory concatenated with a specific config file name
  237. func configPathFor(filename string) string {
  238. path := env.GetConfigPathWithDefault("/models/")
  239. return gopath.Join(path, filename)
  240. }
  241. // Gives the config file name in a full qualified file name
  242. func filenameInConfigPath(fqfn string) string {
  243. _, fileName := gopath.Split(fqfn)
  244. return fileName
  245. }
  246. // ReturnPricingFromConfigs is a safe function to return pricing from configs of opensource to the closed source
  247. // before defaulting it with the above function DefaultPricing
  248. func ReturnPricingFromConfigs(filename string) (*CustomPricing, error) {
  249. if _, err := os.Stat(closedSourceConfigMount); os.IsNotExist(err) {
  250. return &CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: %s likely running in provider config in opencost itself with err: %v", closedSourceConfigMount, err)
  251. }
  252. providerConfigFile := gopath.Join(closedSourceConfigMount, filename)
  253. if _, err := os.Stat(providerConfigFile); err != nil {
  254. return &CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to find file %s with err: %v", providerConfigFile, err)
  255. }
  256. configFile, err := ioutil.ReadFile(providerConfigFile)
  257. if err != nil {
  258. return &CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  259. }
  260. defaultPricing := &CustomPricing{}
  261. err = json.Unmarshal(configFile, defaultPricing)
  262. if err != nil {
  263. return &CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  264. }
  265. return defaultPricing, nil
  266. }