gcpprovider.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. "time"
  17. "k8s.io/klog"
  18. "cloud.google.com/go/bigquery"
  19. "cloud.google.com/go/compute/metadata"
  20. "github.com/kubecost/cost-model/clustercache"
  21. "golang.org/x/oauth2"
  22. "golang.org/x/oauth2/google"
  23. compute "google.golang.org/api/compute/v1"
  24. "google.golang.org/api/iterator"
  25. v1 "k8s.io/api/core/v1"
  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 clustercache.ClusterCache
  41. APIKey string
  42. BaseCPUPrice string
  43. ProjectID string
  44. BillingDataDataset string
  45. DownloadPricingDataLock sync.RWMutex
  46. ReservedInstances []*GCPReservedInstance
  47. Config *ProviderConfig
  48. *CustomProvider
  49. }
  50. type gcpAllocation struct {
  51. Aggregator bigquery.NullString
  52. Environment bigquery.NullString
  53. Service string
  54. Cost float64
  55. }
  56. type multiKeyGCPAllocation struct {
  57. Keys bigquery.NullString
  58. Service string
  59. Cost float64
  60. }
  61. func multiKeyGCPAllocationToOutOfClusterAllocation(gcpAlloc multiKeyGCPAllocation, aggregatorName string) *OutOfClusterAllocation {
  62. var keys []map[string]string
  63. var environment string
  64. if gcpAlloc.Keys.Valid {
  65. err := json.Unmarshal([]byte(gcpAlloc.Keys.StringVal), &keys)
  66. if err != nil {
  67. klog.Infof("Invalid unmarshaling response from BigQuery filtered query: %s", err.Error())
  68. }
  69. for _, label := range keys {
  70. if label["key"] == aggregatorName {
  71. environment = label["value"]
  72. }
  73. break
  74. }
  75. }
  76. return &OutOfClusterAllocation{
  77. Aggregator: aggregatorName,
  78. Environment: environment,
  79. Service: gcpAlloc.Service,
  80. Cost: gcpAlloc.Cost,
  81. }
  82. }
  83. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  84. var aggregator string
  85. if gcpAlloc.Aggregator.Valid {
  86. aggregator = gcpAlloc.Aggregator.StringVal
  87. }
  88. var environment string
  89. if gcpAlloc.Environment.Valid {
  90. environment = gcpAlloc.Environment.StringVal
  91. }
  92. return &OutOfClusterAllocation{
  93. Aggregator: aggregator,
  94. Environment: environment,
  95. Service: gcpAlloc.Service,
  96. Cost: gcpAlloc.Cost,
  97. }
  98. }
  99. func (gcp *GCP) GetLocalStorageQuery(window, offset string, rate bool) string {
  100. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  101. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  102. localStorageCost := 0.04
  103. fmtOffset := ""
  104. if offset != "" {
  105. fmtOffset = fmt.Sprintf("offset %s", offset)
  106. }
  107. fmtCumulativeQuery := `sum(
  108. sum_over_time(container_fs_limit_bytes{device!="tmpfs", id="/"}[%s:1m]%s)
  109. ) by (cluster_id) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  110. fmtMonthlyQuery := `sum(
  111. avg_over_time(container_fs_limit_bytes{device!="tmpfs", id="/"}[%s:1m]%s)
  112. ) by (cluster_id) / 1024 / 1024 / 1024 * %f`
  113. fmtQuery := fmtCumulativeQuery
  114. if rate {
  115. fmtQuery = fmtMonthlyQuery
  116. }
  117. return fmt.Sprintf(fmtQuery, window, fmtOffset, localStorageCost)
  118. }
  119. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  120. c, err := gcp.Config.GetCustomPricingData()
  121. if err != nil {
  122. return nil, err
  123. }
  124. if c.Discount == "" {
  125. c.Discount = "30%"
  126. }
  127. if c.NegotiatedDiscount == "" {
  128. c.NegotiatedDiscount = "0%"
  129. }
  130. return c, nil
  131. }
  132. type BigQueryConfig struct {
  133. ProjectID string `json:"projectID"`
  134. BillingDataDataset string `json:"billingDataDataset"`
  135. Key map[string]string `json:"key"`
  136. }
  137. func (gcp *GCP) GetManagementPlatform() (string, error) {
  138. nodes := gcp.Clientset.GetAllNodes()
  139. if len(nodes) > 0 {
  140. n := nodes[0]
  141. version := n.Status.NodeInfo.KubeletVersion
  142. if strings.Contains(version, "gke") {
  143. return "gke", nil
  144. }
  145. }
  146. return "", nil
  147. }
  148. func (gcp *GCP) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  149. return gcp.Config.UpdateFromMap(a)
  150. }
  151. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  152. return gcp.Config.Update(func(c *CustomPricing) error {
  153. if updateType == BigqueryUpdateType {
  154. a := BigQueryConfig{}
  155. err := json.NewDecoder(r).Decode(&a)
  156. if err != nil {
  157. return err
  158. }
  159. c.ProjectID = a.ProjectID
  160. c.BillingDataDataset = a.BillingDataDataset
  161. j, err := json.Marshal(a.Key)
  162. if err != nil {
  163. return err
  164. }
  165. path := os.Getenv("CONFIG_PATH")
  166. if path == "" {
  167. path = "/models/"
  168. }
  169. keyPath := path + "key.json"
  170. err = ioutil.WriteFile(keyPath, j, 0644)
  171. if err != nil {
  172. return err
  173. }
  174. } else {
  175. a := make(map[string]interface{})
  176. err := json.NewDecoder(r).Decode(&a)
  177. if err != nil {
  178. return err
  179. }
  180. for k, v := range a {
  181. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  182. vstr, ok := v.(string)
  183. if ok {
  184. err := SetCustomPricingField(c, kUpper, vstr)
  185. if err != nil {
  186. return err
  187. }
  188. } else {
  189. sci := v.(map[string]interface{})
  190. sc := make(map[string]string)
  191. for k, val := range sci {
  192. sc[k] = val.(string)
  193. }
  194. c.SharedCosts = sc //todo: support reflection/multiple map fields
  195. }
  196. }
  197. }
  198. remoteEnabled := os.Getenv(remoteEnabled)
  199. if remoteEnabled == "true" {
  200. err := UpdateClusterMeta(os.Getenv(clusterIDKey), c.ClusterName)
  201. if err != nil {
  202. return err
  203. }
  204. }
  205. return nil
  206. })
  207. }
  208. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  209. // "start" and "end" are dates of the format YYYY-MM-DD
  210. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  211. func (gcp *GCP) ExternalAllocations(start string, end string, aggregator string, filterType string, filterValue string) ([]*OutOfClusterAllocation, error) {
  212. c, err := gcp.Config.GetCustomPricingData()
  213. if err != nil {
  214. return nil, err
  215. }
  216. if filterType == "" {
  217. // start, end formatted like: "2019-04-20 00:00:00"
  218. queryString := fmt.Sprintf(`SELECT
  219. service,
  220. labels.key as aggregator,
  221. labels.value as environment,
  222. SUM(cost) as cost
  223. FROM (SELECT
  224. service.description as service,
  225. labels,
  226. cost
  227. FROM %s
  228. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  229. LEFT JOIN UNNEST(labels) as labels
  230. ON labels.key = "%s"
  231. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end, aggregator) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  232. klog.V(4).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  233. return gcp.QuerySQL(queryString)
  234. } else {
  235. queryString := fmt.Sprintf(`(SELECT
  236. service.description as service,
  237. TO_JSON_STRING(labels) as gl,
  238. SUM(cost)
  239. FROM %s
  240. WHERE
  241. EXISTS (SELECT * FROM UNNEST(labels) AS l WHERE l.key = "%s" AND l.value = "%s")
  242. AND EXISTS(SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key = "%s")
  243. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  244. GROUP BY service,gl)`, c.BillingDataDataset, filterType, filterValue, aggregator, start, end)
  245. return gcp.multiLabelQuery(queryString, aggregator)
  246. }
  247. }
  248. /*
  249. (SELECT
  250. service.description as service,
  251. TO_JSON_STRING(labels) as gl,
  252. SUM(cost)
  253. FROM `guestbook-227502.billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2`
  254. WHERE
  255. EXISTS (SELECT * FROM UNNEST(labels) AS l WHERE l.key = "kubernetes_namespace" AND l.value = "kubecost")
  256. AND EXISTS(SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key = "kubernetes_label_app")
  257. AND usage_start_time >= "2020-02-10" AND usage_start_time < "2020-02-13"
  258. GROUP BY service,gl)
  259. */
  260. func (gcp *GCP) multiLabelQuery(query, aggregator string) ([]*OutOfClusterAllocation, error) {
  261. c, err := gcp.Config.GetCustomPricingData()
  262. if err != nil {
  263. return nil, err
  264. }
  265. ctx := context.Background()
  266. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  267. if err != nil {
  268. return nil, err
  269. }
  270. q := client.Query(query)
  271. it, err := q.Read(ctx)
  272. if err != nil {
  273. return nil, err
  274. }
  275. var allocations []*OutOfClusterAllocation
  276. for {
  277. var a multiKeyGCPAllocation
  278. err := it.Next(&a)
  279. if err == iterator.Done {
  280. break
  281. }
  282. if err != nil {
  283. return nil, err
  284. }
  285. allocations = append(allocations, multiKeyGCPAllocationToOutOfClusterAllocation(a, aggregator))
  286. }
  287. return allocations, nil
  288. }
  289. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  290. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  291. c, err := gcp.Config.GetCustomPricingData()
  292. if err != nil {
  293. return nil, err
  294. }
  295. ctx := context.Background()
  296. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  297. if err != nil {
  298. return nil, err
  299. }
  300. q := client.Query(query)
  301. it, err := q.Read(ctx)
  302. if err != nil {
  303. return nil, err
  304. }
  305. var allocations []*OutOfClusterAllocation
  306. for {
  307. var a gcpAllocation
  308. err := it.Next(&a)
  309. if err == iterator.Done {
  310. break
  311. }
  312. if err != nil {
  313. return nil, err
  314. }
  315. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  316. }
  317. return allocations, nil
  318. }
  319. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  320. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  321. remote := os.Getenv(remoteEnabled)
  322. remoteEnabled := false
  323. if os.Getenv(remote) == "true" {
  324. remoteEnabled = true
  325. }
  326. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  327. userAgent: "kubecost",
  328. base: http.DefaultTransport,
  329. }})
  330. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  331. if err != nil {
  332. klog.Infof("Error loading metadata cluster-name: %s", err.Error())
  333. }
  334. c, err := gcp.GetConfig()
  335. if err != nil {
  336. klog.V(1).Infof("Error opening config: %s", err.Error())
  337. }
  338. if c.ClusterName != "" {
  339. attribute = c.ClusterName
  340. }
  341. m := make(map[string]string)
  342. m["name"] = attribute
  343. m["provider"] = "GCP"
  344. m["id"] = os.Getenv(clusterIDKey)
  345. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  346. return m, nil
  347. }
  348. // AddServiceKey adds the service key as required for GetDisks
  349. func (*GCP) AddServiceKey(formValues url.Values) error {
  350. key := formValues.Get("key")
  351. k := []byte(key)
  352. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  353. }
  354. // 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.
  355. func (*GCP) GetDisks() ([]byte, error) {
  356. // metadata API setup
  357. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  358. userAgent: "kubecost",
  359. base: http.DefaultTransport,
  360. }})
  361. projID, err := metadataClient.ProjectID()
  362. if err != nil {
  363. return nil, err
  364. }
  365. client, err := google.DefaultClient(oauth2.NoContext,
  366. "https://www.googleapis.com/auth/compute.readonly")
  367. if err != nil {
  368. return nil, err
  369. }
  370. svc, err := compute.New(client)
  371. if err != nil {
  372. return nil, err
  373. }
  374. res, err := svc.Disks.AggregatedList(projID).Do()
  375. if err != nil {
  376. return nil, err
  377. }
  378. return json.Marshal(res)
  379. }
  380. // GCPPricing represents GCP pricing data for a SKU
  381. type GCPPricing struct {
  382. Name string `json:"name"`
  383. SKUID string `json:"skuId"`
  384. Description string `json:"description"`
  385. Category *GCPResourceInfo `json:"category"`
  386. ServiceRegions []string `json:"serviceRegions"`
  387. PricingInfo []*PricingInfo `json:"pricingInfo"`
  388. ServiceProviderName string `json:"serviceProviderName"`
  389. Node *Node `json:"node"`
  390. PV *PV `json:"pv"`
  391. }
  392. // PricingInfo contains metadata about a cost.
  393. type PricingInfo struct {
  394. Summary string `json:"summary"`
  395. PricingExpression *PricingExpression `json:"pricingExpression"`
  396. CurrencyConversionRate int `json:"currencyConversionRate"`
  397. EffectiveTime string `json:""`
  398. }
  399. // PricingExpression contains metadata about a cost.
  400. type PricingExpression struct {
  401. UsageUnit string `json:"usageUnit"`
  402. UsageUnitDescription string `json:"usageUnitDescription"`
  403. BaseUnit string `json:"baseUnit"`
  404. BaseUnitConversionFactor int64 `json:"-"`
  405. DisplayQuantity int `json:"displayQuantity"`
  406. TieredRates []*TieredRates `json:"tieredRates"`
  407. }
  408. // TieredRates contain data about variable pricing.
  409. type TieredRates struct {
  410. StartUsageAmount int `json:"startUsageAmount"`
  411. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  412. }
  413. // UnitPriceInfo contains data about the actual price being charged.
  414. type UnitPriceInfo struct {
  415. CurrencyCode string `json:"currencyCode"`
  416. Units string `json:"units"`
  417. Nanos float64 `json:"nanos"`
  418. }
  419. // GCPResourceInfo contains metadata about the node.
  420. type GCPResourceInfo struct {
  421. ServiceDisplayName string `json:"serviceDisplayName"`
  422. ResourceFamily string `json:"resourceFamily"`
  423. ResourceGroup string `json:"resourceGroup"`
  424. UsageType string `json:"usageType"`
  425. }
  426. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  427. gcpPricingList := make(map[string]*GCPPricing)
  428. var nextPageToken string
  429. dec := json.NewDecoder(r)
  430. for {
  431. t, err := dec.Token()
  432. if err == io.EOF {
  433. break
  434. }
  435. if t == "skus" {
  436. _, err := dec.Token() // consumes [
  437. if err != nil {
  438. return nil, "", err
  439. }
  440. for dec.More() {
  441. product := &GCPPricing{}
  442. err := dec.Decode(&product)
  443. if err != nil {
  444. return nil, "", err
  445. }
  446. usageType := strings.ToLower(product.Category.UsageType)
  447. instanceType := strings.ToLower(product.Category.ResourceGroup)
  448. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  449. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  450. var nanos float64
  451. if len(product.PricingInfo) > 0 {
  452. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  453. } else {
  454. continue
  455. }
  456. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  457. for _, sr := range product.ServiceRegions {
  458. region := sr
  459. candidateKey := region + "," + "ssd"
  460. if _, ok := pvKeys[candidateKey]; ok {
  461. product.PV = &PV{
  462. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  463. }
  464. gcpPricingList[candidateKey] = product
  465. continue
  466. }
  467. }
  468. continue
  469. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  470. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  471. var nanos float64
  472. if len(product.PricingInfo) > 0 {
  473. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  474. } else {
  475. continue
  476. }
  477. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  478. for _, sr := range product.ServiceRegions {
  479. region := sr
  480. candidateKey := region + "," + "pdstandard"
  481. if _, ok := pvKeys[candidateKey]; ok {
  482. product.PV = &PV{
  483. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  484. }
  485. gcpPricingList[candidateKey] = product
  486. continue
  487. }
  488. }
  489. continue
  490. }
  491. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  492. instanceType = "custom"
  493. }
  494. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") {
  495. instanceType = "n2standard"
  496. }
  497. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  498. instanceType = "e2"
  499. }
  500. partialCPUMap := make(map[string]float64)
  501. partialCPUMap["e2micro"] = 0.25
  502. partialCPUMap["e2small"] = 0.5
  503. partialCPUMap["e2medium"] = 1
  504. /*
  505. var partialCPU float64
  506. if strings.ToLower(instanceType) == "f1micro" {
  507. partialCPU = 0.2
  508. } else if strings.ToLower(instanceType) == "g1small" {
  509. partialCPU = 0.5
  510. }
  511. */
  512. var gpuType string
  513. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  514. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  515. if matchnum == 1 {
  516. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  517. klog.V(4).Info("GPU type found: " + gpuType)
  518. }
  519. }
  520. candidateKeys := []string{}
  521. for _, region := range product.ServiceRegions {
  522. if instanceType == "e2" { // this needs to be done to handle a partial cpu mapping
  523. candidateKeys = append(candidateKeys, region+","+"e2micro"+","+usageType)
  524. candidateKeys = append(candidateKeys, region+","+"e2small"+","+usageType)
  525. candidateKeys = append(candidateKeys, region+","+"e2medium"+","+usageType)
  526. candidateKeys = append(candidateKeys, region+","+"e2standard"+","+usageType)
  527. } else {
  528. candidateKey := region + "," + instanceType + "," + usageType
  529. candidateKeys = append(candidateKeys, candidateKey)
  530. }
  531. }
  532. for _, candidateKey := range candidateKeys {
  533. instanceType = strings.Split(candidateKey, ",")[1] // we may have overriden this while generating candidate keys
  534. region := strings.Split(candidateKey, ",")[0]
  535. candidateKeyGPU := candidateKey + ",gpu"
  536. if gpuType != "" {
  537. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  538. var nanos float64
  539. if len(product.PricingInfo) > 0 {
  540. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  541. } else {
  542. continue
  543. }
  544. hourlyPrice := nanos * math.Pow10(-9)
  545. for k, key := range inputKeys {
  546. if key.GPUType() == gpuType+","+usageType {
  547. if region == strings.Split(k, ",")[0] {
  548. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  549. klog.V(4).Infof("PRODUCT DESCRIPTION: %s", product.Description)
  550. matchedKey := key.Features()
  551. if pl, ok := gcpPricingList[matchedKey]; ok {
  552. pl.Node.GPUName = gpuType
  553. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  554. pl.Node.GPU = "1"
  555. } else {
  556. product.Node = &Node{
  557. GPUName: gpuType,
  558. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  559. GPU: "1",
  560. }
  561. gcpPricingList[matchedKey] = product
  562. }
  563. klog.V(3).Infof("Added data for " + matchedKey)
  564. }
  565. }
  566. }
  567. } else {
  568. _, ok := inputKeys[candidateKey]
  569. _, ok2 := inputKeys[candidateKeyGPU]
  570. if ok || ok2 {
  571. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  572. var nanos float64
  573. if len(product.PricingInfo) > 0 {
  574. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  575. } else {
  576. continue
  577. }
  578. hourlyPrice := nanos * math.Pow10(-9)
  579. if hourlyPrice == 0 {
  580. continue
  581. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  582. if instanceType == "custom" {
  583. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  584. }
  585. if _, ok := gcpPricingList[candidateKey]; ok {
  586. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  587. } else {
  588. product = &GCPPricing{}
  589. product.Node = &Node{
  590. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  591. }
  592. partialCPU, pcok := partialCPUMap[instanceType]
  593. if pcok {
  594. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  595. }
  596. product.Node.UsageType = usageType
  597. gcpPricingList[candidateKey] = product
  598. }
  599. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  600. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  601. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  602. } else {
  603. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  604. product = &GCPPricing{}
  605. product.Node = &Node{
  606. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  607. }
  608. partialCPU, pcok := partialCPUMap[instanceType]
  609. if pcok {
  610. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  611. }
  612. product.Node.UsageType = usageType
  613. gcpPricingList[candidateKeyGPU] = product
  614. }
  615. break
  616. } else {
  617. if _, ok := gcpPricingList[candidateKey]; ok {
  618. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  619. } else {
  620. product = &GCPPricing{}
  621. product.Node = &Node{
  622. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  623. }
  624. partialCPU, pcok := partialCPUMap[instanceType]
  625. if pcok {
  626. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  627. }
  628. product.Node.UsageType = usageType
  629. gcpPricingList[candidateKey] = product
  630. }
  631. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  632. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  633. } else {
  634. product = &GCPPricing{}
  635. product.Node = &Node{
  636. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  637. }
  638. partialCPU, pcok := partialCPUMap[instanceType]
  639. if pcok {
  640. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  641. }
  642. product.Node.UsageType = usageType
  643. gcpPricingList[candidateKeyGPU] = product
  644. }
  645. break
  646. }
  647. }
  648. }
  649. }
  650. }
  651. }
  652. if t == "nextPageToken" {
  653. pageToken, err := dec.Token()
  654. if err != nil {
  655. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  656. return nil, "", err
  657. }
  658. if pageToken.(string) != "" {
  659. nextPageToken = pageToken.(string)
  660. } else {
  661. nextPageToken = "done"
  662. }
  663. }
  664. }
  665. return gcpPricingList, nextPageToken, nil
  666. }
  667. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  668. var pages []map[string]*GCPPricing
  669. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  670. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  671. var parsePagesHelper func(string) error
  672. parsePagesHelper = func(pageToken string) error {
  673. if pageToken == "done" {
  674. return nil
  675. } else if pageToken != "" {
  676. url = url + "&pageToken=" + pageToken
  677. }
  678. resp, err := http.Get(url)
  679. if err != nil {
  680. return err
  681. }
  682. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  683. if err != nil {
  684. return err
  685. }
  686. pages = append(pages, page)
  687. return parsePagesHelper(token)
  688. }
  689. err := parsePagesHelper("")
  690. if err != nil {
  691. return nil, err
  692. }
  693. returnPages := make(map[string]*GCPPricing)
  694. for _, page := range pages {
  695. for k, v := range page {
  696. if val, ok := returnPages[k]; ok { //keys may need to be merged
  697. if val.Node != nil {
  698. if val.Node.VCPUCost == "" {
  699. val.Node.VCPUCost = v.Node.VCPUCost
  700. }
  701. if val.Node.RAMCost == "" {
  702. val.Node.RAMCost = v.Node.RAMCost
  703. }
  704. if val.Node.GPUCost == "" {
  705. val.Node.GPUCost = v.Node.GPUCost
  706. val.Node.GPU = v.Node.GPU
  707. val.Node.GPUName = v.Node.GPUName
  708. }
  709. }
  710. if val.PV != nil {
  711. if val.PV.Cost == "" {
  712. val.PV.Cost = v.PV.Cost
  713. }
  714. }
  715. } else {
  716. returnPages[k] = v
  717. }
  718. }
  719. }
  720. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  721. for k, v := range returnPages {
  722. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  723. }
  724. return returnPages, err
  725. }
  726. // 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.
  727. func (gcp *GCP) DownloadPricingData() error {
  728. gcp.DownloadPricingDataLock.Lock()
  729. defer gcp.DownloadPricingDataLock.Unlock()
  730. c, err := gcp.Config.GetCustomPricingData()
  731. if err != nil {
  732. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  733. return err
  734. }
  735. gcp.BaseCPUPrice = c.CPU
  736. gcp.ProjectID = c.ProjectID
  737. gcp.BillingDataDataset = c.BillingDataDataset
  738. nodeList := gcp.Clientset.GetAllNodes()
  739. inputkeys := make(map[string]Key)
  740. for _, n := range nodeList {
  741. labels := n.GetObjectMeta().GetLabels()
  742. key := gcp.GetKey(labels)
  743. inputkeys[key.Features()] = key
  744. }
  745. pvList := gcp.Clientset.GetAllPersistentVolumes()
  746. storageClasses := gcp.Clientset.GetAllStorageClasses()
  747. storageClassMap := make(map[string]map[string]string)
  748. for _, storageClass := range storageClasses {
  749. params := storageClass.Parameters
  750. storageClassMap[storageClass.ObjectMeta.Name] = params
  751. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  752. storageClassMap["default"] = params
  753. storageClassMap[""] = params
  754. }
  755. }
  756. pvkeys := make(map[string]PVKey)
  757. for _, pv := range pvList {
  758. params, ok := storageClassMap[pv.Spec.StorageClassName]
  759. if !ok {
  760. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  761. continue
  762. }
  763. key := gcp.GetPVKey(pv, params)
  764. pvkeys[key.Features()] = key
  765. }
  766. reserved, err := gcp.getReservedInstances()
  767. if err != nil {
  768. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  769. } else {
  770. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  771. gcp.ReservedInstances = reserved
  772. for _, r := range reserved {
  773. klog.V(1).Infof("%s", r)
  774. }
  775. }
  776. pages, err := gcp.parsePages(inputkeys, pvkeys)
  777. if err != nil {
  778. return err
  779. }
  780. gcp.Pricing = pages
  781. return nil
  782. }
  783. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  784. gcp.DownloadPricingDataLock.RLock()
  785. defer gcp.DownloadPricingDataLock.RUnlock()
  786. pricing, ok := gcp.Pricing[pvk.Features()]
  787. if !ok {
  788. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  789. return &PV{}, nil
  790. }
  791. return pricing.PV, nil
  792. }
  793. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  794. func (gcp *GCP) NetworkPricing() (*Network, error) {
  795. cpricing, err := gcp.Config.GetCustomPricingData()
  796. if err != nil {
  797. return nil, err
  798. }
  799. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  800. if err != nil {
  801. return nil, err
  802. }
  803. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  804. if err != nil {
  805. return nil, err
  806. }
  807. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  808. if err != nil {
  809. return nil, err
  810. }
  811. return &Network{
  812. ZoneNetworkEgressCost: znec,
  813. RegionNetworkEgressCost: rnec,
  814. InternetNetworkEgressCost: inec,
  815. }, nil
  816. }
  817. const (
  818. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  819. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  820. GCPReservedInstanceStatusActive string = "ACTIVE"
  821. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  822. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  823. )
  824. type GCPReservedInstancePlan struct {
  825. Name string
  826. CPUCost float64
  827. RAMCost float64
  828. }
  829. type GCPReservedInstance struct {
  830. ReservedRAM int64
  831. ReservedCPU int64
  832. Plan *GCPReservedInstancePlan
  833. StartDate time.Time
  834. EndDate time.Time
  835. Region string
  836. }
  837. func (r *GCPReservedInstance) String() string {
  838. return fmt.Sprintf("[CPU: %d, RAM: %d, Region: %s, Start: %s, End: %s]", r.ReservedCPU, r.ReservedRAM, r.Region, r.StartDate.String(), r.EndDate.String())
  839. }
  840. type GCPReservedCounter struct {
  841. RemainingCPU int64
  842. RemainingRAM int64
  843. Instance *GCPReservedInstance
  844. }
  845. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  846. return &GCPReservedCounter{
  847. RemainingCPU: instance.ReservedCPU,
  848. RemainingRAM: instance.ReservedRAM,
  849. Instance: instance,
  850. }
  851. }
  852. // Two available Reservation plans for GCP, 1-year and 3-year
  853. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  854. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  855. Name: GCPReservedInstancePlanOneYear,
  856. CPUCost: 0.019915,
  857. RAMCost: 0.002669,
  858. },
  859. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  860. Name: GCPReservedInstancePlanThreeYear,
  861. CPUCost: 0.014225,
  862. RAMCost: 0.001907,
  863. },
  864. }
  865. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  866. numReserved := len(gcp.ReservedInstances)
  867. // Early return if no reserved instance data loaded
  868. if numReserved == 0 {
  869. klog.V(4).Infof("[Reserved] No Reserved Instances")
  870. return
  871. }
  872. now := time.Now()
  873. counters := make(map[string][]*GCPReservedCounter)
  874. for _, r := range gcp.ReservedInstances {
  875. if now.Before(r.StartDate) || now.After(r.EndDate) {
  876. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  877. continue
  878. }
  879. _, ok := counters[r.Region]
  880. counter := newReservedCounter(r)
  881. if !ok {
  882. counters[r.Region] = []*GCPReservedCounter{counter}
  883. } else {
  884. counters[r.Region] = append(counters[r.Region], counter)
  885. }
  886. }
  887. gcpNodes := make(map[string]*v1.Node)
  888. currentNodes := gcp.Clientset.GetAllNodes()
  889. // Create a node name -> node map
  890. for _, gcpNode := range currentNodes {
  891. gcpNodes[gcpNode.GetName()] = gcpNode
  892. }
  893. // go through all provider nodes using k8s nodes for region
  894. for nodeName, node := range nodes {
  895. // Reset reserved allocation to prevent double allocation
  896. node.Reserved = nil
  897. kNode, ok := gcpNodes[nodeName]
  898. if !ok {
  899. klog.V(4).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  900. continue
  901. }
  902. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  903. if !ok {
  904. klog.V(4).Infof("[Reserved] Could not find node region")
  905. continue
  906. }
  907. reservedCounters, ok := counters[nodeRegion]
  908. if !ok {
  909. klog.V(4).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  910. continue
  911. }
  912. node.Reserved = &ReservedInstanceData{
  913. ReservedCPU: 0,
  914. ReservedRAM: 0,
  915. }
  916. for _, reservedCounter := range reservedCounters {
  917. if reservedCounter.RemainingCPU != 0 {
  918. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  919. nodeCPU -= node.Reserved.ReservedCPU
  920. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  921. if reservedCounter.RemainingCPU >= nodeCPU {
  922. reservedCounter.RemainingCPU -= nodeCPU
  923. node.Reserved.ReservedCPU += nodeCPU
  924. } else {
  925. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  926. reservedCounter.RemainingCPU = 0
  927. }
  928. }
  929. if reservedCounter.RemainingRAM != 0 {
  930. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  931. nodeRAM := int64(nodeRAMF)
  932. nodeRAM -= node.Reserved.ReservedRAM
  933. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  934. if reservedCounter.RemainingRAM >= nodeRAM {
  935. reservedCounter.RemainingRAM -= nodeRAM
  936. node.Reserved.ReservedRAM += nodeRAM
  937. } else {
  938. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  939. reservedCounter.RemainingRAM = 0
  940. }
  941. }
  942. }
  943. }
  944. }
  945. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  946. var results []*GCPReservedInstance
  947. ctx := context.Background()
  948. computeService, err := compute.NewService(ctx)
  949. if err != nil {
  950. return nil, err
  951. }
  952. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  953. if err != nil {
  954. return nil, err
  955. }
  956. for regionKey, commitList := range commitments.Items {
  957. for _, commit := range commitList.Commitments {
  958. if commit.Status != GCPReservedInstanceStatusActive {
  959. continue
  960. }
  961. var vcpu int64 = 0
  962. var ram int64 = 0
  963. for _, resource := range commit.Resources {
  964. switch resource.Type {
  965. case GCPReservedInstanceResourceTypeRAM:
  966. ram = resource.Amount * 1024 * 1024
  967. case GCPReservedInstanceResourceTypeCPU:
  968. vcpu = resource.Amount
  969. default:
  970. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  971. }
  972. }
  973. var region string
  974. regionStr := strings.Split(regionKey, "/")
  975. if len(regionStr) == 2 {
  976. region = regionStr[1]
  977. }
  978. timeLayout := "2006-01-02T15:04:05Z07:00"
  979. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  980. if err != nil {
  981. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  982. continue
  983. }
  984. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  985. if err != nil {
  986. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  987. continue
  988. }
  989. // Look for a plan based on the name. Default to One Year if it fails
  990. plan, ok := gcpReservedInstancePlans[commit.Plan]
  991. if !ok {
  992. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  993. }
  994. results = append(results, &GCPReservedInstance{
  995. Region: region,
  996. ReservedRAM: ram,
  997. ReservedCPU: vcpu,
  998. Plan: plan,
  999. StartDate: startTime,
  1000. EndDate: endTime,
  1001. })
  1002. }
  1003. }
  1004. return results, nil
  1005. }
  1006. type pvKey struct {
  1007. Labels map[string]string
  1008. StorageClass string
  1009. StorageClassParameters map[string]string
  1010. }
  1011. func (key *pvKey) GetStorageClass() string {
  1012. return key.StorageClass
  1013. }
  1014. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  1015. return &pvKey{
  1016. Labels: pv.Labels,
  1017. StorageClass: pv.Spec.StorageClassName,
  1018. StorageClassParameters: parameters,
  1019. }
  1020. }
  1021. func (key *pvKey) Features() string {
  1022. // TODO: regional cluster pricing.
  1023. storageClass := key.StorageClassParameters["type"]
  1024. if storageClass == "pd-ssd" {
  1025. storageClass = "ssd"
  1026. } else if storageClass == "pd-standard" {
  1027. storageClass = "pdstandard"
  1028. }
  1029. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  1030. }
  1031. type gcpKey struct {
  1032. Labels map[string]string
  1033. }
  1034. func (gcp *GCP) GetKey(labels map[string]string) Key {
  1035. return &gcpKey{
  1036. Labels: labels,
  1037. }
  1038. }
  1039. func (gcp *gcpKey) ID() string {
  1040. return ""
  1041. }
  1042. func (gcp *gcpKey) GPUType() string {
  1043. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1044. var usageType string
  1045. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1046. usageType = "preemptible"
  1047. } else {
  1048. usageType = "ondemand"
  1049. }
  1050. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  1051. return t + "," + usageType
  1052. }
  1053. return ""
  1054. }
  1055. // GetKey maps node labels to information needed to retrieve pricing data
  1056. func (gcp *gcpKey) Features() string {
  1057. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  1058. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1059. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1060. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1061. instanceType = "e2standard"
  1062. } else if strings.HasPrefix(instanceType, "custom") {
  1063. instanceType = "custom" // The suffix of custom does not matter
  1064. }
  1065. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  1066. var usageType string
  1067. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1068. usageType = "preemptible"
  1069. } else {
  1070. usageType = "ondemand"
  1071. }
  1072. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1073. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1074. }
  1075. return region + "," + instanceType + "," + usageType
  1076. }
  1077. // AllNodePricing returns the GCP pricing objects stored
  1078. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1079. gcp.DownloadPricingDataLock.RLock()
  1080. defer gcp.DownloadPricingDataLock.RUnlock()
  1081. return gcp.Pricing, nil
  1082. }
  1083. // NodePricing returns GCP pricing data for a single node
  1084. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  1085. gcp.DownloadPricingDataLock.RLock()
  1086. defer gcp.DownloadPricingDataLock.RUnlock()
  1087. if n, ok := gcp.Pricing[key.Features()]; ok {
  1088. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1089. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1090. return n.Node, nil
  1091. }
  1092. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  1093. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1094. }