provider.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. package otc
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/opencost/opencost/core/pkg/clustercache"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/core/pkg/opencost"
  13. "github.com/opencost/opencost/core/pkg/util"
  14. "github.com/opencost/opencost/pkg/cloud/models"
  15. "github.com/opencost/opencost/pkg/env"
  16. )
  17. // OTC node pricing attributes
  18. type OTCNodeAttributes struct {
  19. Type string // like s2.large.1
  20. OS string // like windows
  21. Price string // (in EUR) like 0.023
  22. RAM string // (in GB) like 2
  23. VCPU string // like 8
  24. }
  25. type OTCPVAttributes struct {
  26. Type string // like vss.ssd
  27. Price string // (in EUR/GB/h) like 0.01
  28. }
  29. // OTC pricing is either for a node, a persistent volume (or a database, network, cluster, ...)
  30. type OTCPricing struct {
  31. NodeAttributes *OTCNodeAttributes
  32. PVAttributes *OTCPVAttributes
  33. }
  34. // the main provider struct
  35. type OTC struct {
  36. Clientset clustercache.ClusterCache
  37. Pricing map[string]*OTCPricing
  38. Config models.ProviderConfig
  39. ClusterRegion string
  40. projectID string
  41. clusterManagementPrice float64
  42. BaseCPUPrice string
  43. BaseRAMPrice string
  44. BaseGPUPrice string
  45. ValidPricingKeys map[string]bool
  46. DownloadPricingDataLock sync.RWMutex
  47. }
  48. // Kubernetes to OTC OS conversion
  49. /* Note:
  50. Kubernetes cannot fill the "kubernetes.io/os" label with the variety that OTC provides
  51. because it is based on the runtime.GOOS variable (https://kubernetes.io/docs/reference/labels-annotations-taints/#kubernetes-io-os)
  52. which can only contain some os. The pricing between everything but windows differs
  53. by about 5ct - 30ct per hour, so most os get treated like Open Linux.
  54. */
  55. var kubernetesOSTypes = map[string]string{
  56. "linux": "Open Linux",
  57. "windows": "Windows",
  58. "Open Linux": "linux",
  59. "Oracle Linux": "linux",
  60. "SUSE Linux": "linux",
  61. "SUSE for SAP": "linux",
  62. "RedHat Linux": "linux",
  63. "Windows": "windows",
  64. }
  65. // Currently assumes that no GPU is present
  66. // but aws does that too, so its fine.
  67. type otcKey struct {
  68. ProviderID string
  69. Labels map[string]string
  70. }
  71. func (k *otcKey) GPUCount() int {
  72. return 0
  73. }
  74. func (k *otcKey) GPUType() string {
  75. return ""
  76. }
  77. func (k *otcKey) ID() string {
  78. return k.ProviderID
  79. }
  80. type otcPVKey struct {
  81. RegionID string
  82. Type string
  83. Size string // in GB
  84. Labels map[string]string
  85. ProviderId string
  86. StorageClassParameters map[string]string
  87. }
  88. func (k *otcPVKey) Features() string {
  89. fmt.Printf("features for pv %s", k.ID())
  90. return k.RegionID + "," + k.Type
  91. }
  92. func (k *otcKey) Features() string {
  93. instanceType, _ := util.GetInstanceType(k.Labels)
  94. operatingSystem, _ := util.GetOperatingSystem(k.Labels)
  95. ClusterRegion, _ := util.GetRegion(k.Labels)
  96. key := ClusterRegion + "," + instanceType + "," + operatingSystem
  97. return key
  98. }
  99. // Extract/generate a key that holds the data required to calculate
  100. // the cost of the given node (like s2.large.4).
  101. func (otc *OTC) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  102. return &otcKey{
  103. Labels: labels,
  104. ProviderID: labels["providerID"],
  105. }
  106. }
  107. // Returns the storage class for a persistent volume key.
  108. func (k *otcPVKey) GetStorageClass() string {
  109. return k.Type
  110. }
  111. // Returns the provider id for a persistent volume key.
  112. func (k *otcPVKey) ID() string {
  113. return k.ProviderId
  114. }
  115. func (otc *OTC) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  116. providerID := ""
  117. return &otcPVKey{
  118. Labels: pv.Labels,
  119. Type: pv.Spec.StorageClassName,
  120. StorageClassParameters: parameters,
  121. RegionID: defaultRegion,
  122. ProviderId: providerID,
  123. }
  124. }
  125. // Takes a resopnse from the otc api and the respective service name as an input
  126. // and extracts the resulting data into a product slice.
  127. func (otc *OTC) loadStructFromResponse(resp http.Response, serviceName string) ([]Product, error) {
  128. body, err := io.ReadAll(resp.Body)
  129. if err != nil {
  130. return nil, err
  131. }
  132. // Unmarshal the first bit of the response.
  133. wrapper := make(map[string]map[string]interface{})
  134. err = json.Unmarshal(body, &wrapper)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // Unmarshal the second, more specific, bit of the response.
  139. data := make(map[string][]Product)
  140. tmp, err := json.Marshal(wrapper["response"]["result"])
  141. if err != nil {
  142. return nil, err
  143. }
  144. err = json.Unmarshal(tmp, &data)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return data[serviceName], nil
  149. }
  150. // The product (price) data that is fetched from OTC
  151. //
  152. // If OsUnit, VCpu and Ram aren't given, the product
  153. // is a persistent volume, else it's a node.
  154. type Product struct {
  155. OpiFlavour string `json:"opiFlavour"`
  156. OsUnit string `json:"osUnit,omitempty"`
  157. PriceAmount string `json:"priceAmount"`
  158. VCpu string `json:"vCpu,omitempty"`
  159. Ram string `json:"ram,omitempty"`
  160. }
  161. /*
  162. Download the pricing data from the OTC API
  163. When a node has a specified price of e.g. 0.014 and
  164. the kubernetes node has a RAM attribute of 8232873984 Bytes.
  165. The price in Prometheus will be composed of:
  166. - the cpu/h price multiplied with the amount of VCPUs:
  167. 0.006904 * 1 => 0.006904
  168. - the RAM/h price multiplied with the amount of ram in GiB:
  169. 0.000925 * (8232873984/1024/1024/1024) => 0.0070924
  170. And the resulting node_total_hourly_price{} metric in Prometheus
  171. will approach the total node cost retrieved from OTC:
  172. ==> 0.006904 + 0.0070924 = 0.013996399999999999
  173. ~ 0.014
  174. */
  175. func (otc *OTC) DownloadPricingData() error {
  176. otc.DownloadPricingDataLock.Lock()
  177. defer otc.DownloadPricingDataLock.Unlock()
  178. // Fetch pricing data from the otc.json config in case downloading the pricing maps fails.
  179. c, err := otc.Config.GetCustomPricingData()
  180. if err != nil {
  181. log.Errorf("Error downloading default pricing data: %s", err.Error())
  182. }
  183. otc.BaseCPUPrice = c.CPU
  184. otc.BaseRAMPrice = c.RAM
  185. otc.BaseGPUPrice = c.GPU
  186. otc.clusterManagementPrice = 0.10 // TODO: What is the cluster management price?
  187. otc.projectID = c.ProjectID
  188. // Slice with all nodes currently present in the cluster.
  189. nodeList := otc.Clientset.GetAllNodes()
  190. // Slice with all storage classes.
  191. storageClasses := otc.Clientset.GetAllStorageClasses()
  192. for _, tmp := range storageClasses {
  193. fmt.Println("storage class found:")
  194. fmt.Println(tmp.Parameters)
  195. fmt.Println(tmp.Labels)
  196. fmt.Println(tmp.TypeMeta)
  197. fmt.Println(tmp.Size)
  198. }
  199. // Slice with all persistent volumes present in the cluster
  200. pvList := otc.Clientset.GetAllPersistentVolumes()
  201. // Create a slice of all existing keys in the current cluster.
  202. // (keys like "eu-de,s3.medium.1,linux" or "eu-de,s3.xlarge.2,windows")
  203. inputkeys := make(map[string]bool)
  204. tmp := []string{}
  205. for _, node := range nodeList {
  206. labels := node.Labels
  207. key := otc.GetKey(labels, node)
  208. inputkeys[key.Features()] = true
  209. tmp = append(tmp, key.Features())
  210. }
  211. for _, pv := range pvList {
  212. fmt.Println("storage class name \"" + pv.Spec.StorageClassName + "\" found")
  213. key := otc.GetPVKey(pv, map[string]string{}, "eu-de")
  214. inputkeys[key.Features()] = true
  215. tmp = append(tmp, key.Features())
  216. }
  217. otc.Pricing = make(map[string]*OTCPricing)
  218. otc.ValidPricingKeys = make(map[string]bool)
  219. // Get pricing data from API.
  220. nodePricingURL := "https://calculator.otc-service.com/de/open-telekom-price-api/?serviceName=ecs" /* + "&limitMax=200"*/ + "&columns%5B1%5D=opiFlavour" + "&columns%5B2%5D=osUnit" + "&columns%5B3%5D=vCpu" + "&columns%5B4%5D=ram" + "&columns%5B5%5D=priceAmount"
  221. pvPricingURL := "https://calculator.otc-service.com/de/open-telekom-price-api/?serviceName%5B0%5D=evs&columns%5B1%5D=opiFlavour&columns%5B2%5D=priceAmount&limitFrom=0&region%5B3%5D=eu-de"
  222. log.Info("Started downloading OTC pricing data...")
  223. resp, err := http.Get(nodePricingURL)
  224. if err != nil {
  225. return err
  226. }
  227. pvResp, err := http.Get(pvPricingURL)
  228. if err != nil {
  229. return err
  230. }
  231. log.Info("Succesfully downloaded OTC pricing data")
  232. var products []Product
  233. nodeProducts, err := otc.loadStructFromResponse(*resp, "ecs")
  234. if err != nil {
  235. return err
  236. }
  237. products = append(products, nodeProducts...)
  238. pvProducts, err := otc.loadStructFromResponse(*pvResp, "evs")
  239. if err != nil {
  240. return err
  241. }
  242. products = append(products, pvProducts...)
  243. // convert the otc-reponse product-structs to opencost-compatible node structs
  244. const ClusterRegion = "eu-de"
  245. for _, product := range products {
  246. var productPricing *OTCPricing
  247. var key string
  248. // if os is empty the product must be a persistent volume
  249. if product.OsUnit == "" {
  250. productPricing = &OTCPricing{
  251. PVAttributes: &OTCPVAttributes{
  252. Type: product.OpiFlavour,
  253. Price: strings.Split(strings.ReplaceAll(product.PriceAmount, ",", "."), " ")[0],
  254. },
  255. }
  256. key = ClusterRegion + "," + productPricing.PVAttributes.Type
  257. } else {
  258. // else it must be a node
  259. adjustedOS := kubernetesOSTypes[product.OsUnit]
  260. productPricing = &OTCPricing{
  261. NodeAttributes: &OTCNodeAttributes{
  262. Type: product.OpiFlavour,
  263. OS: adjustedOS,
  264. Price: strings.Split(strings.ReplaceAll(product.PriceAmount, ",", "."), " ")[0],
  265. RAM: strings.Split(product.Ram, " ")[0],
  266. VCPU: product.VCpu,
  267. },
  268. }
  269. key = ClusterRegion + "," + productPricing.NodeAttributes.Type + "," + productPricing.NodeAttributes.OS
  270. }
  271. // create a key similiar to the ones created with otcKey.Features()
  272. // so that the pricing data can be fetched using an otcKey
  273. log.Info("product \"" + key + "\" found")
  274. otc.Pricing[key] = productPricing
  275. otc.ValidPricingKeys[key] = true
  276. }
  277. return nil
  278. }
  279. func (otc *OTC) NetworkPricing() (*models.Network, error) {
  280. cpricing, err := otc.Config.GetCustomPricingData()
  281. if err != nil {
  282. return nil, err
  283. }
  284. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  285. if err != nil {
  286. return nil, err
  287. }
  288. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  289. if err != nil {
  290. return nil, err
  291. }
  292. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  293. if err != nil {
  294. return nil, err
  295. }
  296. return &models.Network{
  297. ZoneNetworkEgressCost: znec,
  298. RegionNetworkEgressCost: rnec,
  299. InternetNetworkEgressCost: inec,
  300. }, nil
  301. }
  302. // NodePricing(Key) (*Node, PricingMetadata, error)
  303. // Read the keys features and determine the price of the Node described by
  304. // the key to construct a Pricing Node object to return and work with.
  305. func (otc *OTC) NodePricing(k models.Key) (*models.Node, models.PricingMetadata, error) {
  306. otc.DownloadPricingDataLock.RLock()
  307. defer otc.DownloadPricingDataLock.RUnlock()
  308. key := k.Features()
  309. meta := models.PricingMetadata{}
  310. log.Info("looking for pricing data of node with key features " + key)
  311. pricing, ok := otc.Pricing[key]
  312. if ok {
  313. // The pricing key was found in the pricing list of the otc provider.
  314. // Now create a pricing node from that data and return it.
  315. log.Info("pricing data found")
  316. return otc.createNode(pricing, k)
  317. } else if _, ok := otc.ValidPricingKeys[key]; ok {
  318. // The pricing key is actually valid, but somehow it could not be found.
  319. // Try re-downloading the pricing data to check for changes.
  320. log.Info("key is valid, but no associated pricing data could be found; trying to re-download pricing data")
  321. otc.DownloadPricingDataLock.RUnlock()
  322. err := otc.DownloadPricingData()
  323. otc.DownloadPricingDataLock.RLock()
  324. if err != nil {
  325. return &models.Node{
  326. Cost: otc.BaseCPUPrice,
  327. BaseCPUPrice: otc.BaseCPUPrice,
  328. BaseRAMPrice: otc.BaseRAMPrice,
  329. BaseGPUPrice: otc.BaseGPUPrice,
  330. UsesBaseCPUPrice: true,
  331. }, meta, err
  332. }
  333. pricing, ok = otc.Pricing[key]
  334. if !ok {
  335. // The given key does not exist in OTC or locally, return a default pricing node.
  336. return &models.Node{
  337. Cost: otc.BaseCPUPrice,
  338. BaseCPUPrice: otc.BaseCPUPrice,
  339. BaseRAMPrice: otc.BaseRAMPrice,
  340. BaseGPUPrice: otc.BaseGPUPrice,
  341. UsesBaseCPUPrice: true,
  342. }, meta, fmt.Errorf("unable to find any Pricing data for \"%s\"", key)
  343. }
  344. // The local pricing date was just outdated.
  345. log.Info("pricing data found after re-download")
  346. return otc.createNode(pricing, k)
  347. } else {
  348. // The given key is not valid, fall back to base pricing (handled by the costmodel)?
  349. log.Info("given key \"" + key + "\" is invalid; falling back to default pricing")
  350. return nil, meta, fmt.Errorf("invalid Pricing Key \"%s\"", key)
  351. }
  352. }
  353. // create a Pricing Node from the internal pricing struct and a key describing the kubernetes node
  354. func (otc *OTC) createNode(pricing *OTCPricing, key models.Key) (*models.Node, models.PricingMetadata, error) {
  355. // aws does some fancy stuff here, but it probably isn't that necessary
  356. // so just return the pricing node constructed directly from the internal struct
  357. meta := models.PricingMetadata{}
  358. return &models.Node{
  359. Cost: pricing.NodeAttributes.Price,
  360. VCPU: pricing.NodeAttributes.VCPU,
  361. RAM: pricing.NodeAttributes.RAM,
  362. BaseCPUPrice: otc.BaseCPUPrice,
  363. BaseRAMPrice: otc.BaseRAMPrice,
  364. BaseGPUPrice: otc.BaseGPUPrice,
  365. }, meta, nil
  366. }
  367. // give the order to read the custom provider config file
  368. func (otc *OTC) GetConfig() (*models.CustomPricing, error) {
  369. c, err := otc.Config.GetCustomPricingData()
  370. if err != nil {
  371. return nil, err
  372. }
  373. return c, nil
  374. }
  375. // load balancer cost
  376. // taken straight up from aws
  377. func (otc *OTC) LoadBalancerPricing() (*models.LoadBalancer, error) {
  378. return &models.LoadBalancer{
  379. Cost: 0.05,
  380. }, nil
  381. }
  382. // returns general info about the cluster
  383. // This method HAS to be overwritten as long as the CustomProvider
  384. // Field of the OTC struct is not set when initializing the provider
  385. // in "provider.go" (see all the other providers).
  386. func (otc *OTC) ClusterInfo() (map[string]string, error) {
  387. c, err := otc.GetConfig()
  388. if err != nil {
  389. return nil, err
  390. }
  391. m := make(map[string]string)
  392. m["name"] = "OTC Cluster #1"
  393. if clusterName := otc.getClusterName(c); clusterName != "" {
  394. m["name"] = clusterName
  395. }
  396. m["provider"] = opencost.OTCProvider
  397. m["account"] = c.ProjectID
  398. m["region"] = otc.ClusterRegion
  399. m["remoteReadEnabled"] = strconv.FormatBool(env.IsRemoteEnabled())
  400. m["id"] = env.GetClusterID()
  401. return m, nil
  402. }
  403. func (otc *OTC) getClusterName(cfg *models.CustomPricing) string {
  404. if cfg.ClusterName != "" {
  405. return cfg.ClusterName
  406. }
  407. for _, node := range otc.Clientset.GetAllNodes() {
  408. if clusterName, ok := node.Labels["name"]; ok {
  409. return clusterName
  410. }
  411. }
  412. return ""
  413. }
  414. // search for pricing data matching the given persistent volume key
  415. // in the provider's pricing list and return it
  416. func (otc *OTC) PVPricing(pvk models.PVKey) (*models.PV, error) {
  417. pricing, ok := otc.Pricing[pvk.Features()]
  418. if !ok {
  419. log.Info("Persistent Volume pricing not found for features \"" + pvk.Features() + "\"")
  420. log.Info("continuing with pricing for \"eu-de,vss.ssd\"")
  421. pricing, ok = otc.Pricing["eu-de,vss.ssd"]
  422. if !ok {
  423. log.Errorf("something went wrong, the DownloadPricing method probably didn't execute correctly")
  424. return &models.PV{}, nil
  425. }
  426. }
  427. // otc pv pricing is in the format: price per GB per month
  428. // this convertes that to: GB price per hour
  429. hourly, err := strconv.ParseFloat(pricing.PVAttributes.Price, 32)
  430. if err != nil {
  431. return &models.PV{}, err
  432. }
  433. hourly = hourly / 730
  434. return &models.PV{
  435. Cost: fmt.Sprintf("%v", hourly),
  436. Class: pricing.PVAttributes.Type,
  437. }, nil
  438. }
  439. // TODO: Implement method
  440. func (otc *OTC) GetAddresses() ([]byte, error) {
  441. return []byte{}, nil
  442. }
  443. // TODO: Implement method
  444. func (otc *OTC) GetDisks() ([]byte, error) {
  445. return []byte{}, nil
  446. }
  447. // TODO: Implement method
  448. func (otc *OTC) GetOrphanedResources() ([]models.OrphanedResource, error) {
  449. return []models.OrphanedResource{}, nil
  450. }
  451. // TODO: Implement method
  452. func (otc *OTC) GpuPricing(nodeLabels map[string]string) (string, error) {
  453. return "", nil
  454. }
  455. // TODO: Implement method
  456. func (otc *OTC) AllNodePricing() (interface{}, error) {
  457. return nil, nil
  458. }
  459. // TODO: Implement method
  460. func (otc *OTC) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  461. return &models.CustomPricing{}, nil
  462. }
  463. // TODO: Implement method
  464. func (otc *OTC) UpdateConfigFromConfigMap(configMap map[string]string) (*models.CustomPricing, error) {
  465. return &models.CustomPricing{}, nil
  466. }
  467. // TODO: Implement method
  468. func (otc *OTC) GetManagementPlatform() (string, error) {
  469. return "", nil
  470. }
  471. // TODO: Implement method
  472. func (otc *OTC) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  473. }
  474. func (otc *OTC) ServiceAccountStatus() *models.ServiceAccountStatus {
  475. return &models.ServiceAccountStatus{
  476. Checks: []*models.ServiceAccountCheck{},
  477. }
  478. }
  479. // TODO: Implement method
  480. func (otc *OTC) PricingSourceStatus() map[string]*models.PricingSource {
  481. return map[string]*models.PricingSource{}
  482. }
  483. // TODO: Implement method
  484. func (otc *OTC) ClusterManagementPricing() (string, float64, error) {
  485. return "", 0.0, nil
  486. }
  487. func (otc *OTC) CombinedDiscountForNode(nodeType string, reservedInstance bool, defaultDiscount, negotiatedDiscount float64) float64 {
  488. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  489. }
  490. // Regions retrieved from https://www.open-telekom-cloud.com/de/business-navigator/hochverfuegbare-rechenzentren
  491. var otcRegions = []string{
  492. "eu-de",
  493. "eu-nl",
  494. }
  495. func (otc *OTC) Regions() []string {
  496. regionOverrides := env.GetRegionOverrideList()
  497. if len(regionOverrides) > 0 {
  498. log.Debugf("Overriding OTC regions with configured region list: %+v", regionOverrides)
  499. return regionOverrides
  500. }
  501. return otcRegions
  502. }
  503. // PricingSourceSummary returns the pricing source summary for the provider.
  504. // The summary represents what was _parsed_ from the pricing source, not what
  505. // was returned from the relevant API.
  506. func (otc *OTC) PricingSourceSummary() interface{} {
  507. // encode the pricing source summary as a JSON string
  508. return otc.Pricing
  509. }