providerconfig.go 10 KB

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