providerconfig.go 11 KB

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