gcpprovider.go 38 KB

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