providerconfig.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package provider
  2. import (
  3. "fmt"
  4. "os"
  5. gopath "path"
  6. "strconv"
  7. "sync"
  8. coreenv "github.com/opencost/opencost/core/pkg/env"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/util/json"
  11. "github.com/opencost/opencost/pkg/cloud/alibaba"
  12. "github.com/opencost/opencost/pkg/cloud/aws"
  13. "github.com/opencost/opencost/pkg/cloud/azure"
  14. "github.com/opencost/opencost/pkg/cloud/gcp"
  15. "github.com/opencost/opencost/pkg/cloud/models"
  16. "github.com/opencost/opencost/pkg/cloud/oracle"
  17. "github.com/opencost/opencost/pkg/cloud/otc"
  18. "github.com/opencost/opencost/pkg/cloud/utils"
  19. "github.com/opencost/opencost/pkg/config"
  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(coreenv.GetPathFromConfig(fileName))
  34. pc := &ProviderConfig{
  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 = updateDefaultsOnEmpty(customPricing)
  62. }
  63. }
  64. // Non-ThreadSafe logic to load the config file if a cache does not exist. Flag to write
  65. // the default config if the config file doesn't exist.
  66. func (pc *ProviderConfig) loadConfig(writeIfNotExists bool) (*models.CustomPricing, error) {
  67. if pc.customPricing != nil {
  68. return pc.customPricing, nil
  69. }
  70. exists, err := pc.configFile.Exists()
  71. // File Error other than NotExists
  72. if err != nil {
  73. log.Infof("Custom Pricing file at path '%s' read error: '%s'", pc.configFile.Path(), err.Error())
  74. return DefaultPricing(), err
  75. }
  76. // File Doesn't Exist
  77. if !exists {
  78. pc.customPricing = DefaultPricing()
  79. // If config file is not present use the contents from mount models/ as pricing data
  80. // in closed source rather than from from DefaultPricing as first source of truth.
  81. // since most images will already have a mount, to avail this facility user needs to delete the
  82. // config file manually from configpath else default pricing still holds good.
  83. fileName := filenameInConfigPath(pc.configFile.Path())
  84. defaultPricing, err := ReturnPricingFromConfigs(fileName)
  85. if err == nil {
  86. pc.customPricing = defaultPricing
  87. }
  88. // Only write the file if flag enabled
  89. if writeIfNotExists {
  90. cj, err := json.Marshal(pc.customPricing)
  91. if err != nil {
  92. return pc.customPricing, err
  93. }
  94. err = pc.configFile.Write(cj)
  95. if err != nil {
  96. log.Infof("Could not write Custom Pricing file to path '%s'", pc.configFile.Path())
  97. return pc.customPricing, err
  98. }
  99. }
  100. return pc.customPricing, nil
  101. }
  102. // File Exists - Read all contents of file, unmarshal json
  103. byteValue, err := pc.configFile.Read()
  104. if err != nil {
  105. log.Infof("Could not read Custom Pricing file at path %s", pc.configFile.Path())
  106. // If read fails, we don't want to cache default, assuming that the file is valid
  107. return DefaultPricing(), err
  108. }
  109. var customPricing models.CustomPricing
  110. err = json.Unmarshal(byteValue, &customPricing)
  111. if err != nil {
  112. log.Infof("Could not decode Custom Pricing file at path %s", pc.configFile.Path())
  113. return DefaultPricing(), err
  114. }
  115. pc.customPricing = updateDefaultsOnEmpty(&customPricing)
  116. return pc.customPricing, nil
  117. }
  118. // ThreadSafe method for retrieving the custom pricing config.
  119. func (pc *ProviderConfig) GetCustomPricingData() (*models.CustomPricing, error) {
  120. pc.lock.Lock()
  121. defer pc.lock.Unlock()
  122. return pc.loadConfig(true)
  123. }
  124. // ConfigFileManager returns the ConfigFileManager instance used to manage the CustomPricing
  125. // configuration. In the event of a multi-provider setup, this instance should be used to
  126. // configure any other configuration providers.
  127. func (pc *ProviderConfig) ConfigFileManager() *config.ConfigFileManager {
  128. return pc.configManager
  129. }
  130. // Allows a call to manually update the configuration while maintaining proper thread-safety
  131. // for read/write methods.
  132. func (pc *ProviderConfig) Update(updateFunc func(*models.CustomPricing) error) (*models.CustomPricing, error) {
  133. pc.lock.Lock()
  134. defer pc.lock.Unlock()
  135. // Load Config, set flag to _not_ write if failure to find file.
  136. // We're about to write the updated values, so we don't want to double write.
  137. c, _ := pc.loadConfig(false)
  138. // Execute Update - On error, return the in-memory config but don't update cache
  139. // explicitly
  140. err := updateFunc(c)
  141. if err != nil {
  142. return c, fmt.Errorf("error updating provider config: %w", err)
  143. }
  144. // Cache Update (possible the ptr already references the cached value)
  145. pc.customPricing = updateDefaultsOnEmpty(c)
  146. cj, err := json.Marshal(c)
  147. if err != nil {
  148. return c, fmt.Errorf("error marshaling JSON for provider config: %w", err)
  149. }
  150. err = pc.configFile.Write(cj)
  151. if err != nil {
  152. return c, fmt.Errorf("error writing config file for provider config: %w", err)
  153. }
  154. return c, nil
  155. }
  156. // ThreadSafe update of the config using a string map
  157. func (pc *ProviderConfig) UpdateFromMap(a map[string]string) (*models.CustomPricing, error) {
  158. // Run our Update() method using SetCustomPricingField logic
  159. return pc.Update(func(c *models.CustomPricing) error {
  160. for k, v := range a {
  161. // Just so we consistently supply / receive the same values, uppercase the first letter.
  162. kUpper := utils.ToTitle.String(k)
  163. if kUpper == "CPU" || kUpper == "SpotCPU" || kUpper == "RAM" || kUpper == "SpotRAM" || kUpper == "GPU" || kUpper == "Storage" {
  164. val, err := strconv.ParseFloat(v, 64)
  165. if err != nil {
  166. return fmt.Errorf("unable to parse CPU from string to float: %s", err.Error())
  167. }
  168. v = fmt.Sprintf("%f", val/730)
  169. }
  170. err := models.SetCustomPricingField(c, kUpper, v)
  171. if err != nil {
  172. return fmt.Errorf("error setting custom pricing field: %w", err)
  173. }
  174. }
  175. return nil
  176. })
  177. }
  178. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  179. func DefaultPricing() *models.CustomPricing {
  180. // https://cloud.google.com/compute/all-pricing
  181. return &models.CustomPricing{
  182. Provider: "base",
  183. Description: "Default prices based on GCP us-central1",
  184. // E2 machine types in GCP us-central1 (Iowa)
  185. CPU: "0.021811", // per vCPU hour
  186. SpotCPU: "0.006543", // per vCPU hour
  187. RAM: "0.002923", // per G(i?)B hour
  188. SpotRAM: "0.000877", // per G(i?)B hour
  189. // There are many GPU types. This serves as a reasonably-appropriate
  190. // estimate within a broad range (0.35 up to 3.93)
  191. GPU: "0.95", // per GPU hour
  192. // Same story as above.
  193. SpotGPU: "0.308", // per GPU hour
  194. // This is the "Standard provision space" pricing in the "Disk pricing"
  195. // table.
  196. //
  197. // (($.04 / month) per G(i?)B) *
  198. // month/730 hours =
  199. // 0.00005479452054794521
  200. Storage: "0.00005479452",
  201. ZoneNetworkEgress: "0.01",
  202. RegionNetworkEgress: "0.01",
  203. InternetNetworkEgress: "0.12",
  204. NatGatewayEgress: "0.045",
  205. NatGatewayIngress: "0.045",
  206. CustomPricesEnabled: "false",
  207. }
  208. }
  209. // Helper to default fields that may be left unset or empty due to config age
  210. func updateDefaultsOnEmpty(pricing *models.CustomPricing) *models.CustomPricing {
  211. if pricing == nil {
  212. return pricing
  213. }
  214. defaultPricing := DefaultPricing()
  215. if pricing.SpotGPU == "" {
  216. pricing.SpotGPU = defaultPricing.SpotGPU // Migration for users without this value set by default.
  217. }
  218. if pricing.NatGatewayEgress == "" {
  219. pricing.NatGatewayEgress = defaultPricing.NatGatewayEgress
  220. }
  221. if pricing.NatGatewayIngress == "" {
  222. pricing.NatGatewayIngress = defaultPricing.NatGatewayIngress
  223. }
  224. return pricing
  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 updateDefaultsOnEmpty(defaultPricing), nil
  251. }
  252. func ExtractConfigFromProviders(prov models.Provider) models.ProviderConfig {
  253. if prov == nil {
  254. log.Errorf("cannot extract config from nil provider")
  255. return nil
  256. }
  257. switch p := prov.(type) {
  258. case *CSVProvider:
  259. return ExtractConfigFromProviders(p.CustomProvider)
  260. case *CustomProvider:
  261. return p.Config
  262. case *gcp.GCP:
  263. return p.Config
  264. case *aws.AWS:
  265. return p.Config
  266. case *azure.Azure:
  267. return p.Config
  268. case *alibaba.Alibaba:
  269. return p.Config
  270. case *oracle.Oracle:
  271. return p.Config
  272. case *otc.OTC:
  273. return p.Config
  274. default:
  275. log.Errorf("failed to extract config from provider")
  276. return nil
  277. }
  278. }