provider.go 18 KB

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