providerconfig.go 11 KB

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