providerconfig.go 10 KB

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