customprovider.go 11 KB

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