gcpprovider.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. klog.V(1).Infof("Found match")
  333. product.PV = &PV{
  334. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  335. }
  336. gcpPricingList[candidateKey] = product
  337. continue
  338. }
  339. }
  340. continue
  341. }
  342. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  343. instanceType = "custom"
  344. }
  345. var partialCPU float64
  346. if strings.ToLower(instanceType) == "f1micro" {
  347. partialCPU = 0.2
  348. } else if strings.ToLower(instanceType) == "g1small" {
  349. partialCPU = 0.5
  350. }
  351. var gpuType string
  352. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  353. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  354. if matchnum == 1 {
  355. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  356. klog.V(4).Info("GPU type found: " + gpuType)
  357. }
  358. }
  359. for _, sr := range product.ServiceRegions {
  360. region := sr
  361. candidateKey := region + "," + instanceType + "," + usageType
  362. candidateKeyGPU := candidateKey + ",gpu"
  363. if gpuType != "" {
  364. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  365. var nanos float64
  366. if len(product.PricingInfo) > 0 {
  367. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  368. } else {
  369. continue
  370. }
  371. hourlyPrice := nanos * math.Pow10(-9)
  372. for k, key := range inputKeys {
  373. if key.GPUType() == gpuType {
  374. if region == strings.Split(k, ",")[0] {
  375. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  376. candidateKeyGPU = key.Features()
  377. if pl, ok := gcpPricingList[candidateKeyGPU]; ok {
  378. pl.Node.GPUName = gpuType
  379. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  380. pl.Node.GPU = "1"
  381. } else {
  382. product.Node = &Node{
  383. GPUName: gpuType,
  384. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  385. GPU: "1",
  386. }
  387. klog.V(3).Infof("Added data for " + candidateKeyGPU)
  388. gcpPricingList[candidateKeyGPU] = product
  389. }
  390. }
  391. }
  392. }
  393. } else {
  394. _, ok := inputKeys[candidateKey]
  395. _, ok2 := inputKeys[candidateKeyGPU]
  396. if ok || ok2 {
  397. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  398. var nanos float64
  399. if len(product.PricingInfo) > 0 {
  400. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  401. } else {
  402. continue
  403. }
  404. hourlyPrice := nanos * math.Pow10(-9)
  405. if hourlyPrice == 0 {
  406. continue
  407. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  408. if instanceType == "custom" {
  409. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  410. }
  411. if _, ok := gcpPricingList[candidateKey]; ok {
  412. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  413. } else {
  414. product.Node = &Node{
  415. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  416. }
  417. if partialCPU != 0 {
  418. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  419. }
  420. product.Node.UsageType = usageType
  421. gcpPricingList[candidateKey] = product
  422. }
  423. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  424. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  425. } else {
  426. product.Node = &Node{
  427. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  428. }
  429. if partialCPU != 0 {
  430. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  431. }
  432. product.Node.UsageType = usageType
  433. gcpPricingList[candidateKeyGPU] = product
  434. }
  435. break
  436. } else {
  437. if _, ok := gcpPricingList[candidateKey]; ok {
  438. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  439. } else {
  440. product.Node = &Node{
  441. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  442. }
  443. if partialCPU != 0 {
  444. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  445. }
  446. product.Node.UsageType = usageType
  447. gcpPricingList[candidateKey] = product
  448. }
  449. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  450. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  451. } else {
  452. product.Node = &Node{
  453. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  454. }
  455. if partialCPU != 0 {
  456. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  457. }
  458. product.Node.UsageType = usageType
  459. gcpPricingList[candidateKeyGPU] = product
  460. }
  461. break
  462. }
  463. }
  464. }
  465. }
  466. }
  467. }
  468. if t == "nextPageToken" {
  469. pageToken, err := dec.Token()
  470. if err != nil {
  471. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  472. return nil, "", err
  473. }
  474. if pageToken.(string) != "" {
  475. nextPageToken = pageToken.(string)
  476. } else {
  477. nextPageToken = "done"
  478. }
  479. }
  480. }
  481. return gcpPricingList, nextPageToken, nil
  482. }
  483. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  484. var pages []map[string]*GCPPricing
  485. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  486. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  487. var parsePagesHelper func(string) error
  488. parsePagesHelper = func(pageToken string) error {
  489. if pageToken == "done" {
  490. return nil
  491. } else if pageToken != "" {
  492. url = url + "&pageToken=" + pageToken
  493. }
  494. resp, err := http.Get(url)
  495. if err != nil {
  496. return err
  497. }
  498. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  499. if err != nil {
  500. return err
  501. }
  502. pages = append(pages, page)
  503. return parsePagesHelper(token)
  504. }
  505. err := parsePagesHelper("")
  506. if err != nil {
  507. return nil, err
  508. }
  509. returnPages := make(map[string]*GCPPricing)
  510. for _, page := range pages {
  511. for k, v := range page {
  512. if val, ok := returnPages[k]; ok { //keys may need to be merged
  513. if val.Node != nil {
  514. if val.Node.RAMCost != "" && val.Node.VCPUCost == "" {
  515. val.Node.VCPUCost = v.Node.VCPUCost
  516. } else if val.Node.VCPUCost != "" && val.Node.RAMCost == "" {
  517. val.Node.RAMCost = v.Node.RAMCost
  518. } else {
  519. returnPages[k] = v
  520. }
  521. } else if val.PV != nil {
  522. if val.PV.Cost != "" {
  523. val.PV.Cost = v.PV.Cost
  524. } else {
  525. returnPages[k] = v
  526. }
  527. }
  528. } else {
  529. returnPages[k] = v
  530. }
  531. }
  532. }
  533. return returnPages, err
  534. }
  535. // 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.
  536. func (gcp *GCP) DownloadPricingData() error {
  537. c, err := GetDefaultPricingData("gcp.json")
  538. if err != nil {
  539. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  540. return err
  541. }
  542. gcp.BaseCPUPrice = c.CPU
  543. gcp.ProjectID = c.ProjectID
  544. gcp.BillingDataDataset = c.BillingDataDataset
  545. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  546. if err != nil {
  547. return err
  548. }
  549. inputkeys := make(map[string]Key)
  550. for _, n := range nodeList.Items {
  551. labels := n.GetObjectMeta().GetLabels()
  552. key := gcp.GetKey(labels)
  553. inputkeys[key.Features()] = key
  554. }
  555. pvList, err := gcp.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  556. if err != nil {
  557. return err
  558. }
  559. storageClasses, err := gcp.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  560. storageClassMap := make(map[string]map[string]string)
  561. for _, storageClass := range storageClasses.Items {
  562. params := storageClass.Parameters
  563. storageClassMap[storageClass.ObjectMeta.Name] = params
  564. }
  565. pvkeys := make(map[string]PVKey)
  566. for _, pv := range pvList.Items {
  567. params, ok := storageClassMap[pv.Spec.StorageClassName]
  568. if !ok {
  569. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  570. continue
  571. }
  572. key := gcp.GetPVKey(&pv, params)
  573. pvkeys[key.Features()] = key
  574. }
  575. pages, err := gcp.parsePages(inputkeys, pvkeys)
  576. if err != nil {
  577. return err
  578. }
  579. gcp.Pricing = pages
  580. return nil
  581. }
  582. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  583. pricing, ok := gcp.Pricing[pvk.Features()]
  584. if !ok {
  585. klog.V(2).Infof("Persistent Volume pricing not found for %s", pvk)
  586. return &PV{}, nil
  587. }
  588. return pricing.PV, nil
  589. }
  590. type pvKey struct {
  591. Labels map[string]string
  592. StorageClass string
  593. StorageClassParameters map[string]string
  594. }
  595. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  596. return &pvKey{
  597. Labels: pv.Labels,
  598. StorageClass: pv.Spec.StorageClassName,
  599. StorageClassParameters: parameters,
  600. }
  601. }
  602. func (key *pvKey) Features() string {
  603. storageClass := key.StorageClassParameters["type"]
  604. if storageClass == "pd-ssd" {
  605. storageClass = "ssd"
  606. } else if storageClass == "pd-standard" {
  607. storageClass = "pdstandard"
  608. }
  609. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  610. }
  611. type gcpKey struct {
  612. Labels map[string]string
  613. }
  614. func (gcp *GCP) GetKey(labels map[string]string) Key {
  615. return &gcpKey{
  616. Labels: labels,
  617. }
  618. }
  619. func (gcp *gcpKey) ID() string {
  620. return ""
  621. }
  622. func (gcp *gcpKey) GPUType() string {
  623. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  624. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  625. return t
  626. }
  627. return ""
  628. }
  629. // GetKey maps node labels to information needed to retrieve pricing data
  630. func (gcp *gcpKey) Features() string {
  631. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  632. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  633. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  634. } else if strings.HasPrefix(instanceType, "custom") {
  635. instanceType = "custom" // The suffix of custom does not matter
  636. }
  637. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  638. var usageType string
  639. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  640. usageType = "preemptible"
  641. } else {
  642. usageType = "ondemand"
  643. }
  644. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  645. return region + "," + instanceType + "," + usageType + "," + "gpu"
  646. }
  647. return region + "," + instanceType + "," + usageType
  648. }
  649. // AllNodePricing returns the GCP pricing objects stored
  650. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  651. return gcp.Pricing, nil
  652. }
  653. // NodePricing returns GCP pricing data for a single node
  654. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  655. if n, ok := gcp.Pricing[key.Features()]; ok {
  656. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  657. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  658. return n.Node, nil
  659. }
  660. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  661. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  662. }