gcpprovider.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "k8s.io/klog"
  16. "cloud.google.com/go/bigquery"
  17. "cloud.google.com/go/compute/metadata"
  18. "golang.org/x/oauth2"
  19. "golang.org/x/oauth2/google"
  20. compute "google.golang.org/api/compute/v1"
  21. "google.golang.org/api/iterator"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/client-go/kubernetes"
  25. )
  26. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  27. const BigqueryUpdateType = "bigqueryupdate"
  28. type userAgentTransport struct {
  29. userAgent string
  30. base http.RoundTripper
  31. }
  32. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  33. req.Header.Set("User-Agent", t.userAgent)
  34. return t.base.RoundTrip(req)
  35. }
  36. // GCP implements a provider interface for GCP
  37. type GCP struct {
  38. Pricing map[string]*GCPPricing
  39. Clientset *kubernetes.Clientset
  40. APIKey string
  41. BaseCPUPrice string
  42. ProjectID string
  43. BillingDataDataset string
  44. *CustomProvider
  45. }
  46. type gcpAllocation struct {
  47. Aggregator bigquery.NullString
  48. Environment bigquery.NullString
  49. Service string
  50. Cost float64
  51. }
  52. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  53. var aggregator string
  54. if gcpAlloc.Aggregator.Valid {
  55. aggregator = gcpAlloc.Aggregator.StringVal
  56. }
  57. var environment string
  58. if gcpAlloc.Environment.Valid {
  59. environment = gcpAlloc.Environment.StringVal
  60. }
  61. return &OutOfClusterAllocation{
  62. Aggregator: aggregator,
  63. Environment: environment,
  64. Service: gcpAlloc.Service,
  65. Cost: gcpAlloc.Cost,
  66. }
  67. }
  68. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  69. c, err := GetDefaultPricingData("gcp.json")
  70. if err != nil {
  71. return nil, err
  72. }
  73. return c, nil
  74. }
  75. type BigQueryConfig struct {
  76. ProjectID string `json:"projectID"`
  77. BillingDataDataset string `json:"billingDataDataset"`
  78. Key map[string]string `json:"key"`
  79. }
  80. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  81. c, err := GetDefaultPricingData("gcp.json")
  82. if err != nil {
  83. return nil, err
  84. }
  85. path := os.Getenv("CONFIG_PATH")
  86. if path == "" {
  87. path = "/models/"
  88. }
  89. if updateType == BigqueryUpdateType {
  90. a := BigQueryConfig{}
  91. err = json.NewDecoder(r).Decode(&a)
  92. if err != nil {
  93. return nil, err
  94. }
  95. c.ProjectID = a.ProjectID
  96. c.BillingDataDataset = a.BillingDataDataset
  97. j, err := json.Marshal(a.Key)
  98. if err != nil {
  99. return nil, err
  100. }
  101. keyPath := path + "key.json"
  102. err = ioutil.WriteFile(keyPath, j, 0644)
  103. if err != nil {
  104. return nil, err
  105. }
  106. } else {
  107. a := make(map[string]string)
  108. err = json.NewDecoder(r).Decode(&a)
  109. if err != nil {
  110. return nil, err
  111. }
  112. for k, v := range a {
  113. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  114. err := SetCustomPricingField(c, kUpper, v)
  115. if err != nil {
  116. return nil, err
  117. }
  118. }
  119. }
  120. cj, err := json.Marshal(c)
  121. if err != nil {
  122. return nil, err
  123. }
  124. configPath := path + "gcp.json"
  125. err = ioutil.WriteFile(configPath, cj, 0644)
  126. if err != nil {
  127. return nil, err
  128. }
  129. return c, nil
  130. }
  131. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  132. // "start" and "end" are dates of the format YYYY-MM-DD
  133. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  134. func (gcp *GCP) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  135. c, err := GetDefaultPricingData("gcp.json")
  136. if err != nil {
  137. return nil, err
  138. }
  139. // start, end formatted like: "2019-04-20 00:00:00"
  140. queryString := fmt.Sprintf(`SELECT
  141. service,
  142. labels.key as aggregator,
  143. labels.value as environment,
  144. SUM(cost) as cost
  145. FROM (SELECT
  146. service.description as service,
  147. labels,
  148. cost
  149. FROM %s
  150. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  151. LEFT JOIN UNNEST(labels) as labels
  152. ON labels.key = "kubernetes_namespace" OR labels.key = "kubernetes_container" OR labels.key = "kubernetes_deployment" OR labels.key = "kubernetes_pod" OR labels.key = "kubernetes_daemonset"
  153. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  154. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  155. return gcp.QuerySQL(queryString)
  156. }
  157. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  158. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  159. ctx := context.Background()
  160. client, err := bigquery.NewClient(ctx, gcp.ProjectID) // For example, "guestbook-227502"
  161. if err != nil {
  162. return nil, err
  163. }
  164. q := client.Query(query)
  165. it, err := q.Read(ctx)
  166. if err != nil {
  167. return nil, err
  168. }
  169. var allocations []*OutOfClusterAllocation
  170. for {
  171. var a gcpAllocation
  172. err := it.Next(&a)
  173. if err == iterator.Done {
  174. break
  175. }
  176. if err != nil {
  177. return nil, err
  178. }
  179. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  180. }
  181. return allocations, nil
  182. }
  183. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  184. func (*GCP) ClusterName() ([]byte, error) {
  185. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  186. userAgent: "kubecost",
  187. base: http.DefaultTransport,
  188. }})
  189. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  190. if err != nil {
  191. return nil, err
  192. }
  193. m := make(map[string]string)
  194. m["name"] = attribute
  195. m["provider"] = "GCP"
  196. return json.Marshal(m)
  197. }
  198. // AddServiceKey adds the service key as required for GetDisks
  199. func (*GCP) AddServiceKey(formValues url.Values) error {
  200. key := formValues.Get("key")
  201. k := []byte(key)
  202. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  203. }
  204. // GetDisks returns the GCP disks backing PVs. Useful because sometimes k8s will not clean up PVs correctly. Requires a json config in /var/configs with key region.
  205. func (*GCP) GetDisks() ([]byte, error) {
  206. // metadata API setup
  207. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  208. userAgent: "kubecost",
  209. base: http.DefaultTransport,
  210. }})
  211. projID, err := metadataClient.ProjectID()
  212. if err != nil {
  213. return nil, err
  214. }
  215. client, err := google.DefaultClient(oauth2.NoContext,
  216. "https://www.googleapis.com/auth/compute.readonly")
  217. if err != nil {
  218. return nil, err
  219. }
  220. svc, err := compute.New(client)
  221. if err != nil {
  222. return nil, err
  223. }
  224. res, err := svc.Disks.AggregatedList(projID).Do()
  225. if err != nil {
  226. return nil, err
  227. }
  228. return json.Marshal(res)
  229. }
  230. // GCPPricing represents GCP pricing data for a SKU
  231. type GCPPricing struct {
  232. Name string `json:"name"`
  233. SKUID string `json:"skuId"`
  234. Description string `json:"description"`
  235. Category *GCPResourceInfo `json:"category"`
  236. ServiceRegions []string `json:"serviceRegions"`
  237. PricingInfo []*PricingInfo `json:"pricingInfo"`
  238. ServiceProviderName string `json:"serviceProviderName"`
  239. Node *Node `json:"node"`
  240. PV *PV `json:"pv"`
  241. }
  242. // PricingInfo contains metadata about a cost.
  243. type PricingInfo struct {
  244. Summary string `json:"summary"`
  245. PricingExpression *PricingExpression `json:"pricingExpression"`
  246. CurrencyConversionRate int `json:"currencyConversionRate"`
  247. EffectiveTime string `json:""`
  248. }
  249. // PricingExpression contains metadata about a cost.
  250. type PricingExpression struct {
  251. UsageUnit string `json:"usageUnit"`
  252. UsageUnitDescription string `json:"usageUnitDescription"`
  253. BaseUnit string `json:"baseUnit"`
  254. BaseUnitConversionFactor int64 `json:"-"`
  255. DisplayQuantity int `json:"displayQuantity"`
  256. TieredRates []*TieredRates `json:"tieredRates"`
  257. }
  258. // TieredRates contain data about variable pricing.
  259. type TieredRates struct {
  260. StartUsageAmount int `json:"startUsageAmount"`
  261. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  262. }
  263. // UnitPriceInfo contains data about the actual price being charged.
  264. type UnitPriceInfo struct {
  265. CurrencyCode string `json:"currencyCode"`
  266. Units string `json:"units"`
  267. Nanos float64 `json:"nanos"`
  268. }
  269. // GCPResourceInfo contains metadata about the node.
  270. type GCPResourceInfo struct {
  271. ServiceDisplayName string `json:"serviceDisplayName"`
  272. ResourceFamily string `json:"resourceFamily"`
  273. ResourceGroup string `json:"resourceGroup"`
  274. UsageType string `json:"usageType"`
  275. }
  276. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  277. gcpPricingList := make(map[string]*GCPPricing)
  278. var nextPageToken string
  279. dec := json.NewDecoder(r)
  280. for {
  281. t, err := dec.Token()
  282. if err == io.EOF {
  283. break
  284. }
  285. if t == "skus" {
  286. _, err := dec.Token() // consumes [
  287. if err != nil {
  288. return nil, "", err
  289. }
  290. for dec.More() {
  291. product := &GCPPricing{}
  292. err := dec.Decode(&product)
  293. if err != nil {
  294. return nil, "", err
  295. }
  296. usageType := strings.ToLower(product.Category.UsageType)
  297. instanceType := strings.ToLower(product.Category.ResourceGroup)
  298. if instanceType == "ssd" {
  299. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  300. var nanos float64
  301. if len(product.PricingInfo) > 0 {
  302. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  303. } else {
  304. continue
  305. }
  306. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  307. for _, sr := range product.ServiceRegions {
  308. region := sr
  309. candidateKey := region + "," + "ssd"
  310. if _, ok := pvKeys[candidateKey]; ok {
  311. product.PV = &PV{
  312. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  313. }
  314. gcpPricingList[candidateKey] = product
  315. continue
  316. }
  317. }
  318. continue
  319. } else if instanceType == "pdstandard" {
  320. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  321. var nanos float64
  322. if len(product.PricingInfo) > 0 {
  323. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  324. } else {
  325. continue
  326. }
  327. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  328. for _, sr := range product.ServiceRegions {
  329. region := sr
  330. candidateKey := region + "," + "pdstandard"
  331. if _, ok := pvKeys[candidateKey]; ok {
  332. product.PV = &PV{
  333. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  334. }
  335. gcpPricingList[candidateKey] = product
  336. continue
  337. }
  338. }
  339. continue
  340. }
  341. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  342. instanceType = "custom"
  343. }
  344. var partialCPU float64
  345. if strings.ToLower(instanceType) == "f1micro" {
  346. partialCPU = 0.2
  347. } else if strings.ToLower(instanceType) == "g1small" {
  348. partialCPU = 0.5
  349. }
  350. var gpuType string
  351. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  352. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  353. if matchnum == 1 {
  354. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  355. klog.V(4).Info("GPU type found: " + gpuType)
  356. }
  357. }
  358. for _, sr := range product.ServiceRegions {
  359. region := sr
  360. candidateKey := region + "," + instanceType + "," + usageType
  361. candidateKeyGPU := candidateKey + ",gpu"
  362. if gpuType != "" {
  363. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  364. var nanos float64
  365. if len(product.PricingInfo) > 0 {
  366. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  367. } else {
  368. continue
  369. }
  370. hourlyPrice := nanos * math.Pow10(-9)
  371. for k, key := range inputKeys {
  372. if key.GPUType() == gpuType {
  373. if region == strings.Split(k, ",")[0] {
  374. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  375. candidateKeyGPU = key.Features()
  376. if pl, ok := gcpPricingList[candidateKeyGPU]; ok {
  377. pl.Node.GPUName = gpuType
  378. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  379. pl.Node.GPU = "1"
  380. } else {
  381. product.Node = &Node{
  382. GPUName: gpuType,
  383. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  384. GPU: "1",
  385. }
  386. klog.V(3).Infof("Added data for " + candidateKeyGPU)
  387. gcpPricingList[candidateKeyGPU] = product
  388. }
  389. }
  390. }
  391. }
  392. } else {
  393. _, ok := inputKeys[candidateKey]
  394. _, ok2 := inputKeys[candidateKeyGPU]
  395. if ok || ok2 {
  396. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  397. var nanos float64
  398. if len(product.PricingInfo) > 0 {
  399. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  400. } else {
  401. continue
  402. }
  403. hourlyPrice := nanos * math.Pow10(-9)
  404. if hourlyPrice == 0 {
  405. continue
  406. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  407. if instanceType == "custom" {
  408. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  409. }
  410. if _, ok := gcpPricingList[candidateKey]; ok {
  411. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  412. } else {
  413. product.Node = &Node{
  414. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  415. }
  416. if partialCPU != 0 {
  417. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  418. }
  419. product.Node.UsageType = usageType
  420. gcpPricingList[candidateKey] = product
  421. }
  422. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  423. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  424. } else {
  425. product.Node = &Node{
  426. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  427. }
  428. if partialCPU != 0 {
  429. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  430. }
  431. product.Node.UsageType = usageType
  432. gcpPricingList[candidateKeyGPU] = product
  433. }
  434. break
  435. } else {
  436. if _, ok := gcpPricingList[candidateKey]; ok {
  437. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  438. } else {
  439. product.Node = &Node{
  440. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  441. }
  442. if partialCPU != 0 {
  443. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  444. }
  445. product.Node.UsageType = usageType
  446. gcpPricingList[candidateKey] = product
  447. }
  448. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  449. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  450. } else {
  451. product.Node = &Node{
  452. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  453. }
  454. if partialCPU != 0 {
  455. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  456. }
  457. product.Node.UsageType = usageType
  458. gcpPricingList[candidateKeyGPU] = product
  459. }
  460. break
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. if t == "nextPageToken" {
  468. pageToken, err := dec.Token()
  469. if err != nil {
  470. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  471. return nil, "", err
  472. }
  473. if pageToken.(string) != "" {
  474. nextPageToken = pageToken.(string)
  475. } else {
  476. nextPageToken = "done"
  477. }
  478. }
  479. }
  480. return gcpPricingList, nextPageToken, nil
  481. }
  482. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  483. var pages []map[string]*GCPPricing
  484. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  485. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  486. var parsePagesHelper func(string) error
  487. parsePagesHelper = func(pageToken string) error {
  488. if pageToken == "done" {
  489. return nil
  490. } else if pageToken != "" {
  491. url = url + "&pageToken=" + pageToken
  492. }
  493. resp, err := http.Get(url)
  494. if err != nil {
  495. return err
  496. }
  497. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  498. if err != nil {
  499. return err
  500. }
  501. pages = append(pages, page)
  502. return parsePagesHelper(token)
  503. }
  504. err := parsePagesHelper("")
  505. if err != nil {
  506. return nil, err
  507. }
  508. returnPages := make(map[string]*GCPPricing)
  509. for _, page := range pages {
  510. for k, v := range page {
  511. if val, ok := returnPages[k]; ok { //keys may need to be merged
  512. if val.Node != nil {
  513. if val.Node.RAMCost != "" && val.Node.VCPUCost == "" {
  514. val.Node.VCPUCost = v.Node.VCPUCost
  515. } else if val.Node.VCPUCost != "" && val.Node.RAMCost == "" {
  516. val.Node.RAMCost = v.Node.RAMCost
  517. } else {
  518. returnPages[k] = v
  519. }
  520. } else if val.PV != nil {
  521. if val.PV.Cost != "" {
  522. val.PV.Cost = v.PV.Cost
  523. } else {
  524. returnPages[k] = v
  525. }
  526. }
  527. } else {
  528. returnPages[k] = v
  529. }
  530. }
  531. }
  532. return returnPages, err
  533. }
  534. // DownloadPricingData fetches data from the GCP Pricing API. Requires a key-- a kubecost key is provided for quickstart, but should be replaced by a users.
  535. func (gcp *GCP) DownloadPricingData() error {
  536. c, err := GetDefaultPricingData("gcp.json")
  537. if err != nil {
  538. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  539. return err
  540. }
  541. gcp.BaseCPUPrice = c.CPU
  542. gcp.ProjectID = c.ProjectID
  543. gcp.BillingDataDataset = c.BillingDataDataset
  544. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  545. if err != nil {
  546. return err
  547. }
  548. inputkeys := make(map[string]Key)
  549. for _, n := range nodeList.Items {
  550. labels := n.GetObjectMeta().GetLabels()
  551. key := gcp.GetKey(labels)
  552. inputkeys[key.Features()] = key
  553. }
  554. pvList, err := gcp.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  555. if err != nil {
  556. return err
  557. }
  558. storageClasses, err := gcp.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  559. storageClassMap := make(map[string]map[string]string)
  560. for _, storageClass := range storageClasses.Items {
  561. params := storageClass.Parameters
  562. storageClassMap[storageClass.ObjectMeta.Name] = params
  563. }
  564. pvkeys := make(map[string]PVKey)
  565. for _, pv := range pvList.Items {
  566. params, ok := storageClassMap[pv.Spec.StorageClassName]
  567. if !ok {
  568. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  569. continue
  570. }
  571. key := gcp.GetPVKey(&pv, params)
  572. pvkeys[key.Features()] = key
  573. }
  574. pages, err := gcp.parsePages(inputkeys, pvkeys)
  575. if err != nil {
  576. return err
  577. }
  578. gcp.Pricing = pages
  579. return nil
  580. }
  581. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  582. pricing, ok := gcp.Pricing[pvk.Features()]
  583. if !ok {
  584. klog.V(2).Infof("Persistent Volume pricing not found for %s", pvk)
  585. return &PV{}, nil
  586. }
  587. return pricing.PV, nil
  588. }
  589. type pvKey struct {
  590. Labels map[string]string
  591. StorageClass string
  592. StorageClassParameters map[string]string
  593. }
  594. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  595. return &pvKey{
  596. Labels: pv.Labels,
  597. StorageClass: pv.Spec.StorageClassName,
  598. StorageClassParameters: parameters,
  599. }
  600. }
  601. func (key *pvKey) Features() string {
  602. storageClass := key.StorageClassParameters["type"]
  603. if storageClass == "pd-ssd" {
  604. storageClass = "ssd"
  605. } else if storageClass == "pd-standard" {
  606. storageClass = "pdstandard"
  607. }
  608. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  609. }
  610. type gcpKey struct {
  611. Labels map[string]string
  612. }
  613. func (gcp *GCP) GetKey(labels map[string]string) Key {
  614. return &gcpKey{
  615. Labels: labels,
  616. }
  617. }
  618. func (gcp *gcpKey) ID() string {
  619. return ""
  620. }
  621. func (gcp *gcpKey) GPUType() string {
  622. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  623. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  624. return t
  625. }
  626. return ""
  627. }
  628. // GetKey maps node labels to information needed to retrieve pricing data
  629. func (gcp *gcpKey) Features() string {
  630. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  631. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  632. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  633. } else if strings.HasPrefix(instanceType, "custom") {
  634. instanceType = "custom" // The suffix of custom does not matter
  635. }
  636. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  637. var usageType string
  638. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  639. usageType = "preemptible"
  640. } else {
  641. usageType = "ondemand"
  642. }
  643. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  644. return region + "," + instanceType + "," + usageType + "," + "gpu"
  645. }
  646. return region + "," + instanceType + "," + usageType
  647. }
  648. // AllNodePricing returns the GCP pricing objects stored
  649. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  650. return gcp.Pricing, nil
  651. }
  652. // NodePricing returns GCP pricing data for a single node
  653. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  654. if n, ok := gcp.Pricing[key.Features()]; ok {
  655. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  656. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  657. return n.Node, nil
  658. }
  659. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  660. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  661. }