2
0

customprovider.go 11 KB

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