gcpprovider.go 22 KB

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