gcpprovider.go 38 KB

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