customprovider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package provider
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/opencost"
  11. "github.com/opencost/opencost/core/pkg/util"
  12. "github.com/opencost/opencost/core/pkg/util/json"
  13. "github.com/opencost/opencost/pkg/cloud/models"
  14. "github.com/opencost/opencost/pkg/cloud/utils"
  15. "github.com/opencost/opencost/pkg/clustercache"
  16. "github.com/opencost/opencost/pkg/env"
  17. )
  18. type NodePrice struct {
  19. CPU string
  20. RAM string
  21. GPU string
  22. }
  23. type CustomProvider struct {
  24. Clientset clustercache.ClusterCache
  25. Pricing map[string]*NodePrice
  26. SpotLabel string
  27. SpotLabelValue string
  28. GPULabel string
  29. GPULabelValue string
  30. ClusterRegion string
  31. ClusterAccountID string
  32. DownloadPricingDataLock sync.RWMutex
  33. Config models.ProviderConfig
  34. }
  35. var volTypes = map[string]string{
  36. "EBS:VolumeUsage.gp2": "gp2",
  37. "EBS:VolumeUsage.gp3": "gp3",
  38. "EBS:VolumeUsage": "standard",
  39. "EBS:VolumeUsage.sc1": "sc1",
  40. "EBS:VolumeP-IOPS.piops": "io1",
  41. "EBS:VolumeUsage.st1": "st1",
  42. "EBS:VolumeUsage.piops": "io1",
  43. "gp2": "EBS:VolumeUsage.gp2",
  44. "gp3": "EBS:VolumeUsage.gp3",
  45. "standard": "EBS:VolumeUsage",
  46. "sc1": "EBS:VolumeUsage.sc1",
  47. "io1": "EBS:VolumeUsage.piops",
  48. "st1": "EBS:VolumeUsage.st1",
  49. }
  50. type customPVKey struct {
  51. Labels map[string]string
  52. StorageClassParameters map[string]string
  53. StorageClassName string
  54. Name string
  55. DefaultRegion string
  56. ProviderID string
  57. }
  58. // PricingSourceSummary returns the pricing source summary for the provider.
  59. // The summary represents what was _parsed_ from the pricing source, not what
  60. // was returned from the relevant API.
  61. func (cp *CustomProvider) PricingSourceSummary() interface{} {
  62. return cp.Pricing
  63. }
  64. type customProviderKey struct {
  65. SpotLabel string
  66. SpotLabelValue string
  67. GPULabel string
  68. GPULabelValue string
  69. Labels map[string]string
  70. }
  71. func (*CustomProvider) ClusterManagementPricing() (string, float64, error) {
  72. return "", 0.0, nil
  73. }
  74. func (*CustomProvider) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  75. return ""
  76. }
  77. func (cp *CustomProvider) GetConfig() (*models.CustomPricing, error) {
  78. return cp.Config.GetCustomPricingData()
  79. }
  80. func (*CustomProvider) GetManagementPlatform() (string, error) {
  81. return "", nil
  82. }
  83. func (*CustomProvider) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  84. }
  85. func (cp *CustomProvider) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  86. return cp.Config.UpdateFromMap(a)
  87. }
  88. func (cp *CustomProvider) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  89. // Parse config updates from reader
  90. a := make(map[string]interface{})
  91. err := json.NewDecoder(r).Decode(&a)
  92. if err != nil {
  93. return nil, err
  94. }
  95. // Update Config
  96. c, err := cp.Config.Update(func(c *models.CustomPricing) error {
  97. for k, v := range a {
  98. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  99. vstr, ok := v.(string)
  100. if ok {
  101. err := models.SetCustomPricingField(c, kUpper, vstr)
  102. if err != nil {
  103. return fmt.Errorf("error setting custom pricing field: %w", err)
  104. }
  105. } else {
  106. return fmt.Errorf("type error while updating config for %s", kUpper)
  107. }
  108. }
  109. return nil
  110. })
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer cp.DownloadPricingData()
  115. return c, nil
  116. }
  117. func (cp *CustomProvider) ClusterInfo() (map[string]string, error) {
  118. conf, err := cp.GetConfig()
  119. if err != nil {
  120. return nil, err
  121. }
  122. m := make(map[string]string)
  123. if conf.ClusterName != "" {
  124. m["name"] = conf.ClusterName
  125. }
  126. m["provider"] = opencost.CustomProvider
  127. m["region"] = cp.ClusterRegion
  128. m["account"] = cp.ClusterAccountID
  129. m["id"] = env.GetClusterID()
  130. return m, nil
  131. }
  132. func (*CustomProvider) GetAddresses() ([]byte, error) {
  133. return nil, nil
  134. }
  135. func (*CustomProvider) GetDisks() ([]byte, error) {
  136. return nil, nil
  137. }
  138. func (*CustomProvider) GetOrphanedResources() ([]models.OrphanedResource, error) {
  139. return nil, errors.New("not implemented")
  140. }
  141. func (cp *CustomProvider) AllNodePricing() (interface{}, error) {
  142. cp.DownloadPricingDataLock.RLock()
  143. defer cp.DownloadPricingDataLock.RUnlock()
  144. return cp.Pricing, nil
  145. }
  146. func (cp *CustomProvider) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  147. cp.DownloadPricingDataLock.RLock()
  148. defer cp.DownloadPricingDataLock.RUnlock()
  149. meta := models.PricingMetadata{}
  150. k := key.Features()
  151. var gpuCount string
  152. if _, ok := cp.Pricing[k]; !ok {
  153. // Default is saying that there is no pricing info for the cluster and we should fall back to the default values.
  154. // An interesting case is if the default values weren't loaded.
  155. k = "default"
  156. }
  157. if key.GPUType() != "" {
  158. k += ",gpu" // TODO: support multiple custom gpu types.
  159. gpuCount = "1" // TODO: support more than one gpu.
  160. }
  161. var cpuCost, ramCost, gpuCost string
  162. if pricing, ok := cp.Pricing[k]; !ok {
  163. log.Warnf("No pricing found for key=%s, setting values to 0", k)
  164. cpuCost = "0.0"
  165. ramCost = "0.0"
  166. gpuCost = "0.0"
  167. } else {
  168. cpuCost = pricing.CPU
  169. ramCost = pricing.RAM
  170. gpuCost = pricing.GPU
  171. }
  172. return &models.Node{
  173. VCPUCost: cpuCost,
  174. RAMCost: ramCost,
  175. GPUCost: gpuCost,
  176. GPU: gpuCount,
  177. }, meta, nil
  178. }
  179. func (cp *CustomProvider) DownloadPricingData() error {
  180. cp.DownloadPricingDataLock.Lock()
  181. defer cp.DownloadPricingDataLock.Unlock()
  182. if cp.Pricing == nil {
  183. m := make(map[string]*NodePrice)
  184. cp.Pricing = m
  185. }
  186. p, err := cp.Config.GetCustomPricingData()
  187. if err != nil {
  188. return err
  189. }
  190. cp.SpotLabel = p.SpotLabel
  191. cp.SpotLabelValue = p.SpotLabelValue
  192. cp.GPULabel = p.GpuLabel
  193. cp.GPULabelValue = p.GpuLabelValue
  194. cp.Pricing["default"] = &NodePrice{
  195. CPU: p.CPU,
  196. RAM: p.RAM,
  197. }
  198. cp.Pricing["default,spot"] = &NodePrice{
  199. CPU: p.SpotCPU,
  200. RAM: p.SpotRAM,
  201. }
  202. cp.Pricing["default,gpu"] = &NodePrice{
  203. CPU: p.CPU,
  204. RAM: p.RAM,
  205. GPU: p.GPU,
  206. }
  207. return nil
  208. }
  209. func (cp *CustomProvider) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  210. return &customProviderKey{
  211. SpotLabel: cp.SpotLabel,
  212. SpotLabelValue: cp.SpotLabelValue,
  213. GPULabel: cp.GPULabel,
  214. GPULabelValue: cp.GPULabelValue,
  215. Labels: labels,
  216. }
  217. }
  218. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  219. // "start" and "end" are dates of the format YYYY-MM-DD
  220. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  221. func (*CustomProvider) ExternalAllocations(start string, end string, aggregator []string, filterType string, filterValue string, crossCluster bool) ([]*models.OutOfClusterAllocation, error) {
  222. return nil, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  223. }
  224. func (*CustomProvider) QuerySQL(query string) ([]byte, error) {
  225. return nil, nil
  226. }
  227. func (cp *CustomProvider) PVPricing(pvk models.PVKey) (*models.PV, error) {
  228. cpricing, err := cp.Config.GetCustomPricingData()
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &models.PV{
  233. Cost: cpricing.Storage,
  234. }, nil
  235. }
  236. func (cp *CustomProvider) NetworkPricing() (*models.Network, error) {
  237. cpricing, err := cp.Config.GetCustomPricingData()
  238. if err != nil {
  239. return nil, err
  240. }
  241. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  242. if err != nil {
  243. return nil, err
  244. }
  245. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  246. if err != nil {
  247. return nil, err
  248. }
  249. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return &models.Network{
  254. ZoneNetworkEgressCost: znec,
  255. RegionNetworkEgressCost: rnec,
  256. InternetNetworkEgressCost: inec,
  257. }, nil
  258. }
  259. func (cp *CustomProvider) LoadBalancerPricing() (*models.LoadBalancer, error) {
  260. cpricing, err := cp.Config.GetCustomPricingData()
  261. if err != nil {
  262. return nil, err
  263. }
  264. fffrc, err := strconv.ParseFloat(cpricing.FirstFiveForwardingRulesCost, 64)
  265. if err != nil {
  266. return nil, err
  267. }
  268. afrc, err := strconv.ParseFloat(cpricing.AdditionalForwardingRuleCost, 64)
  269. if err != nil {
  270. return nil, err
  271. }
  272. lbidc, err := strconv.ParseFloat(cpricing.LBIngressDataCost, 64)
  273. if err != nil {
  274. return nil, err
  275. }
  276. var totalCost float64
  277. numForwardingRules := 1.0 // hard-code at 1 for now
  278. dataIngressGB := 0.0 // hard-code at 0 for now
  279. if numForwardingRules < 5 {
  280. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  281. } else {
  282. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  283. }
  284. return &models.LoadBalancer{
  285. Cost: totalCost,
  286. }, nil
  287. }
  288. func (*CustomProvider) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  289. return &customPVKey{
  290. Labels: pv.Labels,
  291. StorageClassName: pv.Spec.StorageClassName,
  292. StorageClassParameters: parameters,
  293. DefaultRegion: defaultRegion,
  294. }
  295. }
  296. func (key *customPVKey) ID() string {
  297. return key.ProviderID
  298. }
  299. func (key *customPVKey) GetStorageClass() string {
  300. return key.StorageClassName
  301. }
  302. // Features returns a comma separated string of features for a given PV
  303. // (@pokom): This was imported from aws which caused a cyclical dependency. This _should_ be refactored to be specific to a custom pvkey
  304. func (key *customPVKey) Features() string {
  305. storageClass := key.StorageClassParameters["type"]
  306. if storageClass == "standard" {
  307. storageClass = "gp2"
  308. }
  309. // Storage class names are generally EBS volume types (gp2)
  310. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  311. // Converts between the 2
  312. region, ok := util.GetRegion(key.Labels)
  313. if !ok {
  314. region = key.DefaultRegion
  315. }
  316. class, ok := volTypes[storageClass]
  317. if !ok {
  318. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  319. }
  320. return region + "," + class
  321. }
  322. func (k *customProviderKey) GPUCount() int {
  323. return 0
  324. }
  325. func (cpk *customProviderKey) GPUType() string {
  326. if t, ok := cpk.Labels[cpk.GPULabel]; ok {
  327. return t
  328. }
  329. return ""
  330. }
  331. func (cpk *customProviderKey) ID() string {
  332. return ""
  333. }
  334. func (cpk *customProviderKey) Features() string {
  335. if cpk.Labels[cpk.SpotLabel] != "" && cpk.Labels[cpk.SpotLabel] == cpk.SpotLabelValue {
  336. return "default,spot"
  337. }
  338. return "default" // TODO: multiple custom pricing support.
  339. }
  340. func (cp *CustomProvider) ServiceAccountStatus() *models.ServiceAccountStatus {
  341. return &models.ServiceAccountStatus{
  342. Checks: []*models.ServiceAccountCheck{},
  343. }
  344. }
  345. func (cp *CustomProvider) PricingSourceStatus() map[string]*models.PricingSource {
  346. return make(map[string]*models.PricingSource)
  347. }
  348. func (cp *CustomProvider) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  349. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  350. }
  351. func (cp *CustomProvider) Regions() []string {
  352. return []string{}
  353. }