customprovider.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. const defaultClusterName = "Custom Cluster"
  121. clusterID := coreenv.GetClusterID()
  122. if clusterID == "" {
  123. clusterID = "default-cluster"
  124. }
  125. clusterName := conf.ClusterName
  126. if clusterName == "" {
  127. if clusterName = coreenv.GetClusterID(); clusterName == "" {
  128. clusterName = defaultClusterName
  129. }
  130. }
  131. m := make(map[string]string)
  132. m["name"] = clusterName
  133. m["provider"] = opencost.CustomProvider
  134. m["region"] = cp.ClusterRegion
  135. m["account"] = cp.ClusterAccountID
  136. m["id"] = clusterID
  137. return m, nil
  138. }
  139. func (*CustomProvider) GetAddresses() ([]byte, error) {
  140. return nil, nil
  141. }
  142. func (*CustomProvider) GetDisks() ([]byte, error) {
  143. return nil, nil
  144. }
  145. func (*CustomProvider) GetOrphanedResources() ([]models.OrphanedResource, error) {
  146. return nil, errors.New("not implemented")
  147. }
  148. func (cp *CustomProvider) AllNodePricing() (interface{}, error) {
  149. cp.DownloadPricingDataLock.RLock()
  150. defer cp.DownloadPricingDataLock.RUnlock()
  151. return cp.Pricing, nil
  152. }
  153. func (cp *CustomProvider) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  154. cp.DownloadPricingDataLock.RLock()
  155. defer cp.DownloadPricingDataLock.RUnlock()
  156. meta := models.PricingMetadata{}
  157. k := key.Features()
  158. var gpuCount string
  159. if _, ok := cp.Pricing[k]; !ok {
  160. // Default is saying that there is no pricing info for the cluster and we should fall back to the default values.
  161. // An interesting case is if the default values weren't loaded.
  162. k = "default"
  163. }
  164. if key.GPUType() != "" {
  165. k += ",gpu" // TODO: support multiple custom gpu types.
  166. if key.GPUCount() > 0 {
  167. gpuCount = strconv.Itoa(key.GPUCount())
  168. } else {
  169. gpuCount = "1"
  170. }
  171. }
  172. var cpuCost, ramCost, gpuCost string
  173. if pricing, ok := cp.Pricing[k]; !ok {
  174. log.Warnf("No pricing found for key=%s, setting values to 0", k)
  175. cpuCost = "0.0"
  176. ramCost = "0.0"
  177. gpuCost = "0.0"
  178. } else {
  179. cpuCost = pricing.CPU
  180. ramCost = pricing.RAM
  181. gpuCost = pricing.GPU
  182. }
  183. return &models.Node{
  184. VCPUCost: cpuCost,
  185. RAMCost: ramCost,
  186. GPUCost: gpuCost,
  187. GPU: gpuCount,
  188. }, meta, nil
  189. }
  190. func (cp *CustomProvider) DownloadPricingData() error {
  191. cp.DownloadPricingDataLock.Lock()
  192. defer cp.DownloadPricingDataLock.Unlock()
  193. if cp.Pricing == nil {
  194. m := make(map[string]*NodePrice)
  195. cp.Pricing = m
  196. }
  197. p, err := cp.Config.GetCustomPricingData()
  198. if err != nil {
  199. return err
  200. }
  201. cp.SpotLabel = p.SpotLabel
  202. cp.SpotLabelValue = p.SpotLabelValue
  203. cp.GPULabel = p.GpuLabel
  204. cp.GPULabelValue = p.GpuLabelValue
  205. cp.Pricing["default"] = &NodePrice{
  206. CPU: p.CPU,
  207. RAM: p.RAM,
  208. }
  209. cp.Pricing["default,spot"] = &NodePrice{
  210. CPU: p.SpotCPU,
  211. RAM: p.SpotRAM,
  212. }
  213. cp.Pricing["default,gpu"] = &NodePrice{
  214. CPU: p.CPU,
  215. RAM: p.RAM,
  216. GPU: p.GPU,
  217. }
  218. return nil
  219. }
  220. func (cp *CustomProvider) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  221. gpuTypeName := ""
  222. gpuCount := 0
  223. if n != nil {
  224. if gpu, ok := n.Status.Capacity["nvidia.com/gpu"]; ok && gpu.Value() > 0 {
  225. gpuTypeName = "nvidia.com/gpu"
  226. gpuCount = int(gpu.Value())
  227. } else if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok && vgpu.Value() > 0 {
  228. gpuTypeName = "k8s.amazonaws.com/vgpu"
  229. gpuCount = int(vgpu.Value())
  230. }
  231. }
  232. return &customProviderKey{
  233. SpotLabel: cp.SpotLabel,
  234. SpotLabelValue: cp.SpotLabelValue,
  235. GPULabel: cp.GPULabel,
  236. GPULabelValue: cp.GPULabelValue,
  237. GPUTypeName: gpuTypeName,
  238. GPUCountValue: gpuCount,
  239. Labels: labels,
  240. }
  241. }
  242. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  243. // "start" and "end" are dates of the format YYYY-MM-DD
  244. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  245. func (*CustomProvider) ExternalAllocations(start string, end string, aggregator []string, filterType string, filterValue string, crossCluster bool) ([]*models.OutOfClusterAllocation, error) {
  246. return nil, nil // TODO: transform the QuerySQL lines into the new OutOfClusterAllocation Struct
  247. }
  248. func (*CustomProvider) QuerySQL(query string) ([]byte, error) {
  249. return nil, nil
  250. }
  251. func (cp *CustomProvider) GpuPricing(nodeLabels map[string]string) (string, error) {
  252. return "", nil
  253. }
  254. func (cp *CustomProvider) PVPricing(pvk models.PVKey) (*models.PV, error) {
  255. cpricing, err := cp.Config.GetCustomPricingData()
  256. if err != nil {
  257. return nil, err
  258. }
  259. return &models.PV{
  260. Cost: cpricing.Storage,
  261. }, nil
  262. }
  263. func (cp *CustomProvider) NetworkPricing() (*models.Network, error) {
  264. cpricing, err := cp.Config.GetCustomPricingData()
  265. if err != nil {
  266. return nil, err
  267. }
  268. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  269. if err != nil {
  270. return nil, err
  271. }
  272. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  273. if err != nil {
  274. return nil, err
  275. }
  276. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  277. if err != nil {
  278. return nil, err
  279. }
  280. nge, err := strconv.ParseFloat(cpricing.NatGatewayEgress, 64)
  281. if err != nil {
  282. return nil, err
  283. }
  284. ngi, err := strconv.ParseFloat(cpricing.NatGatewayIngress, 64)
  285. if err != nil {
  286. return nil, err
  287. }
  288. return &models.Network{
  289. ZoneNetworkEgressCost: znec,
  290. RegionNetworkEgressCost: rnec,
  291. InternetNetworkEgressCost: inec,
  292. NatGatewayEgressCost: nge,
  293. NatGatewayIngressCost: ngi,
  294. }, nil
  295. }
  296. func parsePriceOrZero(field, value string) (float64, error) {
  297. if value == "" {
  298. return 0, nil
  299. }
  300. price, err := strconv.ParseFloat(value, 64)
  301. if err != nil {
  302. return 0, fmt.Errorf("invalid custom pricing value %q for %s: %w", value, field, err)
  303. }
  304. return price, nil
  305. }
  306. func (cp *CustomProvider) LoadBalancerPricing() (*models.LoadBalancer, error) {
  307. cpricing, err := cp.Config.GetCustomPricingData()
  308. if err != nil {
  309. return nil, err
  310. }
  311. firstFiveForwardingRulesCostField := "firstFiveForwardingRulesCost"
  312. firstFiveForwardingRulesCost := cpricing.FirstFiveForwardingRulesCost
  313. if firstFiveForwardingRulesCost == "" && cpricing.DefaultLBPrice != "" {
  314. firstFiveForwardingRulesCostField = "defaultLBPrice"
  315. firstFiveForwardingRulesCost = cpricing.DefaultLBPrice
  316. }
  317. fffrc, err := parsePriceOrZero(firstFiveForwardingRulesCostField, firstFiveForwardingRulesCost)
  318. if err != nil {
  319. return nil, err
  320. }
  321. afrc, err := parsePriceOrZero("additionalForwardingRuleCost", cpricing.AdditionalForwardingRuleCost)
  322. if err != nil {
  323. return nil, err
  324. }
  325. lbidc, err := parsePriceOrZero("LBIngressDataCost", cpricing.LBIngressDataCost)
  326. if err != nil {
  327. return nil, err
  328. }
  329. var totalCost float64
  330. numForwardingRules := 1.0 // hard-code at 1 for now
  331. dataIngressGB := 0.0 // hard-code at 0 for now
  332. if numForwardingRules < 5 {
  333. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  334. } else {
  335. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  336. }
  337. return &models.LoadBalancer{
  338. Cost: totalCost,
  339. }, nil
  340. }
  341. func (*CustomProvider) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  342. return &customPVKey{
  343. Labels: pv.Labels,
  344. StorageClassName: pv.Spec.StorageClassName,
  345. StorageClassParameters: parameters,
  346. DefaultRegion: defaultRegion,
  347. }
  348. }
  349. func (key *customPVKey) ID() string {
  350. return key.ProviderID
  351. }
  352. func (key *customPVKey) GetStorageClass() string {
  353. return key.StorageClassName
  354. }
  355. // Features returns a comma separated string of features for a given PV
  356. // (@pokom): This was imported from aws which caused a cyclical dependency. This _should_ be refactored to be specific to a custom pvkey
  357. func (key *customPVKey) Features() string {
  358. storageClass := key.StorageClassParameters["type"]
  359. if storageClass == "standard" {
  360. storageClass = "gp2"
  361. }
  362. // Storage class names are generally EBS volume types (gp2)
  363. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  364. // Converts between the 2
  365. region, ok := util.GetRegion(key.Labels)
  366. if !ok {
  367. region = key.DefaultRegion
  368. }
  369. class, ok := volTypes[storageClass]
  370. if !ok {
  371. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  372. }
  373. return region + "," + class
  374. }
  375. func (k *customProviderKey) GPUCount() int {
  376. return k.GPUCountValue
  377. }
  378. func (cpk *customProviderKey) GPUType() string {
  379. if cpk.GPULabel != "" {
  380. if t, ok := cpk.Labels[cpk.GPULabel]; ok {
  381. return t
  382. }
  383. }
  384. return cpk.GPUTypeName
  385. }
  386. func (cpk *customProviderKey) ID() string {
  387. return ""
  388. }
  389. func (cpk *customProviderKey) Features() string {
  390. if cpk.Labels[cpk.SpotLabel] != "" && cpk.Labels[cpk.SpotLabel] == cpk.SpotLabelValue {
  391. return "default,spot"
  392. }
  393. return "default" // TODO: multiple custom pricing support.
  394. }
  395. func (cp *CustomProvider) ServiceAccountStatus() *models.ServiceAccountStatus {
  396. return &models.ServiceAccountStatus{
  397. Checks: []*models.ServiceAccountCheck{},
  398. }
  399. }
  400. func (cp *CustomProvider) PricingSourceStatus() map[string]*models.PricingSource {
  401. return make(map[string]*models.PricingSource)
  402. }
  403. func (cp *CustomProvider) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  404. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  405. }
  406. func (cp *CustomProvider) Regions() []string {
  407. return []string{}
  408. }