gcpprovider.go 37 KB

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