providerconfig.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/types"
  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 *types.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(types.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 = types.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) (*types.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 types.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 = types.DefaultShareTenancyCost
  123. }
  124. return pc.customPricing, nil
  125. }
  126. // ThreadSafe method for retrieving the custom pricing config.
  127. func (pc *ProviderConfig) GetCustomPricingData() (*types.CustomPricing, error) {
  128. pc.lock.Lock()
  129. defer pc.lock.Unlock()
  130. return pc.loadConfig(true)
  131. }
  132. // ConfigFileManager returns the ConfigFileManager instance used to manage the CustomPricing
  133. // configuration. In the event of a multi-provider setup, this instance should be used to
  134. // configure any other configuration providers.
  135. func (pc *ProviderConfig) ConfigFileManager() *config.ConfigFileManager {
  136. return pc.configManager
  137. }
  138. // Allows a call to manually update the configuration while maintaining proper thread-safety
  139. // for read/write methods.
  140. func (pc *ProviderConfig) Update(updateFunc func(*types.CustomPricing) error) (*types.CustomPricing, error) {
  141. pc.lock.Lock()
  142. defer pc.lock.Unlock()
  143. // Load Config, set flag to _not_ write if failure to find file.
  144. // We're about to write the updated values, so we don't want to double write.
  145. c, _ := pc.loadConfig(false)
  146. // Execute Update - On error, return the in-memory config but don't update cache
  147. // explicitly
  148. err := updateFunc(c)
  149. if err != nil {
  150. return c, err
  151. }
  152. // Cache Update (possible the ptr already references the cached value)
  153. pc.customPricing = c
  154. cj, err := json.Marshal(c)
  155. if err != nil {
  156. return c, err
  157. }
  158. err = pc.configFile.Write(cj)
  159. if err != nil {
  160. return c, err
  161. }
  162. return c, nil
  163. }
  164. // ThreadSafe update of the config using a string map
  165. func (pc *ProviderConfig) UpdateFromMap(a map[string]string) (*types.CustomPricing, error) {
  166. // Run our Update() method using SetCustomPricingField logic
  167. return pc.Update(func(c *types.CustomPricing) error {
  168. for k, v := range a {
  169. // Just so we consistently supply / receive the same values, uppercase the first letter.
  170. kUpper := types.ToTitle.String(k)
  171. if kUpper == "CPU" || kUpper == "SpotCPU" || kUpper == "RAM" || kUpper == "SpotRAM" || kUpper == "GPU" || kUpper == "Storage" {
  172. val, err := strconv.ParseFloat(v, 64)
  173. if err != nil {
  174. return fmt.Errorf("Unable to parse CPU from string to float: %s", err.Error())
  175. }
  176. v = fmt.Sprintf("%f", val/730)
  177. }
  178. err := types.SetCustomPricingField(c, kUpper, v)
  179. if err != nil {
  180. return err
  181. }
  182. }
  183. return nil
  184. })
  185. }
  186. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  187. func DefaultPricing() *types.CustomPricing {
  188. // https://cloud.google.com/compute/all-pricing
  189. return &types.CustomPricing{
  190. Provider: "base",
  191. Description: "Default prices based on GCP us-central1",
  192. // E2 machine types in GCP us-central1 (Iowa)
  193. CPU: "0.021811", // per vCPU hour
  194. SpotCPU: "0.006543", // per vCPU hour
  195. RAM: "0.002923", // per G(i?)B hour
  196. SpotRAM: "0.000877", // per G(i?)B hour
  197. // There are many GPU types. This serves as a reasonably-appropriate
  198. // estimate within a broad range (0.35 up to 3.93)
  199. GPU: "0.95", // per GPU hour
  200. // Same story as above.
  201. SpotGPU: "0.308", // per GPU hour
  202. // This is the "Standard provision space" pricing in the "Disk pricing"
  203. // table.
  204. //
  205. // (($.04 / month) per G(i?)B) *
  206. // month/730 hours =
  207. // 0.00005479452054794521
  208. Storage: "0.00005479452",
  209. ZoneNetworkEgress: "0.01",
  210. RegionNetworkEgress: "0.01",
  211. InternetNetworkEgress: "0.12",
  212. CustomPricesEnabled: "false",
  213. ShareTenancyCosts: "true",
  214. }
  215. }
  216. // Returns the configuration directory concatenated with a specific config file name
  217. func configPathFor(filename string) string {
  218. path := env.GetConfigPathWithDefault("/models/")
  219. return gopath.Join(path, filename)
  220. }
  221. // Gives the config file name in a full qualified file name
  222. func filenameInConfigPath(fqfn string) string {
  223. _, fileName := gopath.Split(fqfn)
  224. return fileName
  225. }
  226. // ReturnPricingFromConfigs is a safe function to return pricing from configs of opensource to the closed source
  227. // before defaulting it with the above function DefaultPricing
  228. func ReturnPricingFromConfigs(filename string) (*types.CustomPricing, error) {
  229. if _, err := os.Stat(closedSourceConfigMount); os.IsNotExist(err) {
  230. return &types.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: %s likely running in provider config in opencost itself with err: %v", closedSourceConfigMount, err)
  231. }
  232. providerConfigFile := gopath.Join(closedSourceConfigMount, filename)
  233. if _, err := os.Stat(providerConfigFile); err != nil {
  234. return &types.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to find file %s with err: %v", providerConfigFile, err)
  235. }
  236. configFile, err := ioutil.ReadFile(providerConfigFile)
  237. if err != nil {
  238. return &types.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  239. }
  240. defaultPricing := &types.CustomPricing{}
  241. err = json.Unmarshal(configFile, defaultPricing)
  242. if err != nil {
  243. return &types.CustomPricing{}, fmt.Errorf("ReturnPricingFromConfigs: unable to open file %s with err: %v", providerConfigFile, err)
  244. }
  245. return defaultPricing, nil
  246. }