customprovider.go 12 KB

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