providerconfig.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package cloud
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. gopath "path"
  7. "strconv"
  8. "sync"
  9. "github.com/opencost/opencost/pkg/cloud/models"
  10. "github.com/opencost/opencost/pkg/cloud/utils"
  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. // 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 *models.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(models.CustomPricing)
  52. err := json.Unmarshal(data, customPricing)
  53. if err != nil {
  54. log.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 = models.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) (*models.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. log.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. log.Infof("Could not find Custom Pricing file at path '%s'", pc.configFile.Path())
  81. pc.customPricing = DefaultPricing()
  82. // If config file is not present use the contents from mount models/ as pricing data
  83. // in closed source rather than from from DefaultPricing as first source of truth.
  84. // since most images will already have a mount, to avail this facility user needs to delete the
  85. // config file manually from configpath else default pricing still holds good.
  86. fileName := filenameInConfigPath(pc.configFile.Path())
  87. defaultPricing, err := ReturnPricingFromConfigs(fileName)
  88. if err == nil {
  89. pc.customPricing = defaultPricing
  90. }
  91. // Only write the file if flag enabled
  92. if writeIfNotExists {
  93. cj, err := json.Marshal(pc.customPricing)
  94. if err != nil {
  95. return pc.customPricing, err
  96. }
  97. err = pc.configFile.Write(cj)
  98. if err != nil {
  99. log.Infof("Could not write Custom Pricing file to path '%s'", pc.configFile.Path())
  100. return pc.customPricing, err
  101. }
  102. }
  103. return pc.customPricing, nil
  104. }
  105. // File Exists - Read all contents of file, unmarshal json
  106. byteValue, err := pc.configFile.Read()
  107. if err != nil {
  108. log.Infof("Could not read Custom Pricing file at path %s", pc.configFile.Path())
  109. // If read fails, we don't want to cache default, assuming that the file is valid
  110. return DefaultPricing(), err
  111. }
  112. var customPricing models.CustomPricing
  113. err = json.Unmarshal(byteValue, &customPricing)
  114. if err != nil {
  115. log.Infof("Could not decode Custom Pricing file at path %s", pc.configFile.Path())
  116. return DefaultPricing(), err
  117. }
  118. pc.customPricing = &customPricing
  119. if pc.customPricing.SpotGPU == "" {
  120. pc.customPricing.SpotGPU = DefaultPricing().SpotGPU // Migration for users without this value set by default.
  121. }
  122. if pc.customPricing.ShareTenancyCosts == "" {
  123. pc.customPricing.ShareTenancyCosts = models.DefaultShareTenancyCost
  124. }
  125. return pc.customPricing, nil
  126. }
  127. // ThreadSafe method for retrieving the custom pricing config.
  128. func (pc *ProviderConfig) GetCustomPricingData() (*models.CustomPricing, error) {
  129. pc.lock.Lock()
  130. defer pc.lock.Unlock()
  131. return pc.loadConfig(true)
  132. }
  133. // ConfigFileManager returns the ConfigFileManager instance used to manage the CustomPricing
  134. // configuration. In the event of a multi-provider setup, this instance should be used to
  135. // configure any other configuration providers.
  136. func (pc *ProviderConfig) ConfigFileManager() *config.ConfigFileManager {
  137. return pc.configManager
  138. }
  139. // Allows a call to manually update the configuration while maintaining proper thread-safety
  140. // for read/write methods.
  141. func (pc *ProviderConfig) Update(updateFunc func(*models.CustomPricing) error) (*models.CustomPricing, error) {
  142. pc.lock.Lock()
  143. defer pc.lock.Unlock()
  144. // Load Config, set flag to _not_ write if failure to find file.
  145. // We're about to write the updated values, so we don't want to double write.
  146. c, _ := pc.loadConfig(false)
  147. // Execute Update - On error, return the in-memory config but don't update cache
  148. // explicitly
  149. err := updateFunc(c)
  150. if err != nil {
  151. return c, err
  152. }
  153. // Cache Update (possible the ptr already references the cached value)
  154. pc.customPricing = c
  155. cj, err := json.Marshal(c)
  156. if err != nil {
  157. return c, err
  158. }
  159. err = pc.configFile.Write(cj)
  160. if err != nil {
  161. return c, err
  162. }
  163. return c, nil
  164. }
  165. // ThreadSafe update of the config using a string map
  166. func (pc *ProviderConfig) UpdateFromMap(a map[string]string) (*models.CustomPricing, error) {
  167. // Run our Update() method using SetCustomPricingField logic
  168. return pc.Update(func(c *models.CustomPricing) error {
  169. for k, v := range a {
  170. // Just so we consistently supply / receive the same values, uppercase the first letter.
  171. kUpper := utils.ToTitle.String(k)
  172. if kUpper == "CPU" || kUpper == "SpotCPU" || kUpper == "RAM" || kUpper == "SpotRAM" || kUpper == "GPU" || kUpper == "Storage" {
  173. val, err := strconv.ParseFloat(v, 64)
  174. if err != nil {
  175. return fmt.Errorf("Unable to parse CPU from string to float: %s", err.Error())
  176. }
  177. v = fmt.Sprintf("%f", val/730)
  178. }
  179. err := models.SetCustomPricingField(c, kUpper, v)
  180. if err != nil {
  181. return err
  182. }
  183. }
  184. return nil
  185. })
  186. }
  187. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  188. func DefaultPricing() *models.CustomPricing {
  189. // https://cloud.google.com/compute/all-pricing
  190. return &models.CustomPricing{
  191. Provider: "base",
  192. Description: "Default prices based on GCP us-central1",
  193. // E2 machine types in GCP us-central1 (Iowa)
  194. CPU: "0.021811", // per vCPU hour
  195. SpotCPU: "0.006543", // per vCPU hour
  196. RAM: "0.002923", // per G(i?)B hour
  197. SpotRAM: "0.000877", // per G(i?)B hour
  198. // There are many GPU types. This serves as a reasonably-appropriate
  199. // estimate within a broad range (0.35 up to 3.93)
  200. GPU: "0.95", // per GPU hour
  201. // Same story as above.
  202. SpotGPU: "0.308", // per GPU hour
  203. // This is the "Standard provision space" pricing in the "Disk pricing"
  204. // table.
  205. //
  206. // (($.04 / month) per G(i?)B) *
  207. // month/730 hours =
  208. // 0.00005479452054794521
  209. Storage: "0.00005479452",
  210. ZoneNetworkEgress: "0.01",
  211. RegionNetworkEgress: "0.01",
  212. InternetNetworkEgress: "0.12",
  213. CustomPricesEnabled: "false",
  214. ShareTenancyCosts: "true",
  215. }
  216. }
  217. // Returns the configuration directory concatenated with a specific config file name
  218. func configPathFor(filename string) string {
  219. path := env.GetConfigPathWithDefault("/models/")
  220. return gopath.Join(path, filename)
  221. }
  222. // Gives the config file name in a full qualified file name
  223. func filenameInConfigPath(fqfn string) string {
  224. _, fileName := gopath.Split(fqfn)
  225. return fileName
  226. }
  227. // ReturnPricingFromConfigs is a safe function to return pricing from configs of opensource to the closed source
  228. // before defaulting it with the above function DefaultPricing
  229. func ReturnPricingFromConfigs(filename string) (*models.CustomPricing, error) {
  230. if _, err := os.Stat(closedSourceConfigMount); os.IsNotExist(err) {
  231. return &models.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: %s likely running in provider config in opencost itself with err: %v", closedSourceConfigMount, err)
  232. }
  233. providerConfigFile := gopath.Join(closedSourceConfigMount, filename)
  234. if _, err := os.Stat(providerConfigFile); err != nil {
  235. return &models.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to find file %s with err: %v", providerConfigFile, err)
  236. }
  237. configFile, err := ioutil.ReadFile(providerConfigFile)
  238. if err != nil {
  239. return &models.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  240. }
  241. defaultPricing := &models.CustomPricing{}
  242. err = json.Unmarshal(configFile, defaultPricing)
  243. if err != nil {
  244. return &models.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  245. }
  246. return defaultPricing, nil
  247. }