customprovider.go 11 KB

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