customprovider.go 13 KB

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