providerconfig.go 11 KB

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