2
0

customprovider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package provider
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/opencost/opencost/pkg/cloud/models"
  10. "github.com/opencost/opencost/pkg/cloud/utils"
  11. "github.com/opencost/opencost/pkg/clustercache"
  12. "github.com/opencost/opencost/pkg/env"
  13. "github.com/opencost/opencost/pkg/kubecost"
  14. "github.com/opencost/opencost/pkg/log"
  15. "github.com/opencost/opencost/pkg/util"
  16. "github.com/opencost/opencost/pkg/util/json"
  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 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"] = kubecost.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, error) {
  148. cp.DownloadPricingDataLock.RLock()
  149. defer cp.DownloadPricingDataLock.RUnlock()
  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. }, 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 *v1.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) PVPricing(pvk models.PVKey) (*models.PV, error) {
  228. cpricing, err := cp.Config.GetCustomPricingData()
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &models.PV{
  233. Cost: cpricing.Storage,
  234. }, nil
  235. }
  236. func (cp *CustomProvider) NetworkPricing() (*models.Network, error) {
  237. cpricing, err := cp.Config.GetCustomPricingData()
  238. if err != nil {
  239. return nil, err
  240. }
  241. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  242. if err != nil {
  243. return nil, err
  244. }
  245. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  246. if err != nil {
  247. return nil, err
  248. }
  249. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return &models.Network{
  254. ZoneNetworkEgressCost: znec,
  255. RegionNetworkEgressCost: rnec,
  256. InternetNetworkEgressCost: inec,
  257. }, nil
  258. }
  259. func (cp *CustomProvider) LoadBalancerPricing() (*models.LoadBalancer, error) {
  260. cpricing, err := cp.Config.GetCustomPricingData()
  261. if err != nil {
  262. return nil, err
  263. }
  264. fffrc, err := strconv.ParseFloat(cpricing.FirstFiveForwardingRulesCost, 64)
  265. if err != nil {
  266. return nil, err
  267. }
  268. afrc, err := strconv.ParseFloat(cpricing.AdditionalForwardingRuleCost, 64)
  269. if err != nil {
  270. return nil, err
  271. }
  272. lbidc, err := strconv.ParseFloat(cpricing.LBIngressDataCost, 64)
  273. if err != nil {
  274. return nil, err
  275. }
  276. var totalCost float64
  277. numForwardingRules := 1.0 // hard-code at 1 for now
  278. dataIngressGB := 0.0 // hard-code at 0 for now
  279. if numForwardingRules < 5 {
  280. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  281. } else {
  282. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  283. }
  284. return &models.LoadBalancer{
  285. Cost: totalCost,
  286. }, nil
  287. }
  288. func (*CustomProvider) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  289. return &customPVKey{
  290. Labels: pv.Labels,
  291. StorageClassName: pv.Spec.StorageClassName,
  292. StorageClassParameters: parameters,
  293. DefaultRegion: defaultRegion,
  294. }
  295. }
  296. func (key *customPVKey) ID() string {
  297. return key.ProviderID
  298. }
  299. func (key *customPVKey) GetStorageClass() string {
  300. return key.StorageClassName
  301. }
  302. // Features returns a comma separated string of features for a given PV
  303. // (@pokom): This was imported from aws which caused a cyclical dependency. This _should_ be refactored to be specific to a custom pvkey
  304. func (key *customPVKey) Features() string {
  305. storageClass := key.StorageClassParameters["type"]
  306. if storageClass == "standard" {
  307. storageClass = "gp2"
  308. }
  309. // Storage class names are generally EBS volume types (gp2)
  310. // Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
  311. // Converts between the 2
  312. region, ok := util.GetRegion(key.Labels)
  313. if !ok {
  314. region = key.DefaultRegion
  315. }
  316. class, ok := volTypes[storageClass]
  317. if !ok {
  318. log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
  319. }
  320. return region + "," + class
  321. }
  322. func (k *customProviderKey) GPUCount() int {
  323. return 0
  324. }
  325. func (cpk *customProviderKey) GPUType() string {
  326. if t, ok := cpk.Labels[cpk.GPULabel]; ok {
  327. return t
  328. }
  329. return ""
  330. }
  331. func (cpk *customProviderKey) ID() string {
  332. return ""
  333. }
  334. func (cpk *customProviderKey) Features() string {
  335. if cpk.Labels[cpk.SpotLabel] != "" && cpk.Labels[cpk.SpotLabel] == cpk.SpotLabelValue {
  336. return "default,spot"
  337. }
  338. return "default" // TODO: multiple custom pricing support.
  339. }
  340. func (cp *CustomProvider) ServiceAccountStatus() *models.ServiceAccountStatus {
  341. return &models.ServiceAccountStatus{
  342. Checks: []*models.ServiceAccountCheck{},
  343. }
  344. }
  345. func (cp *CustomProvider) PricingSourceStatus() map[string]*models.PricingSource {
  346. return make(map[string]*models.PricingSource)
  347. }
  348. func (cp *CustomProvider) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  349. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  350. }
  351. func (cp *CustomProvider) Regions() []string {
  352. return []string{}
  353. }