gcpprovider.go 38 KB

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