gcpprovider.go 39 KB

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