gcpprovider.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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(`(
  310. SELECT
  311. service.description as service,
  312. TO_JSON_STRING(labels) as keys,
  313. SUM(cost) as cost
  314. FROM %s
  315. WHERE 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
  318. )`, c.BillingDataDataset, aggregator, start, end)
  319. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  320. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  321. s = append(s, gcpOOC...)
  322. qerr = err
  323. } else {
  324. if filterType == "kubernetes_labels" {
  325. fvs := strings.Split(filterValue, "=")
  326. if len(fvs) == 2 {
  327. filterType = fvs[0]
  328. filterValue = fvs[1]
  329. } else {
  330. klog.V(2).Infof("[Warning] illegal kubernetes_labels filterValue: %s", filterValue)
  331. }
  332. }
  333. queryString := fmt.Sprintf(`(
  334. SELECT
  335. service.description as service,
  336. TO_JSON_STRING(labels) as keys,
  337. SUM(cost) as cost
  338. FROM %s
  339. WHERE EXISTS (SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key IN (%s))
  340. AND EXISTS (SELECT * FROM UNNEST(labels) AS l WHERE l.key = "%s" AND l.value = "%s")
  341. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  342. GROUP BY service, keys
  343. )`, c.BillingDataDataset, aggregator, filterType, filterValue, start, end)
  344. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  345. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  346. s = append(s, gcpOOC...)
  347. qerr = err
  348. }
  349. if qerr != nil {
  350. klog.Infof("Error querying gcp: %s", qerr)
  351. }
  352. return s, qerr
  353. }
  354. func (gcp *GCP) multiLabelQuery(query string, aggregators []string) ([]*OutOfClusterAllocation, error) {
  355. c, err := gcp.Config.GetCustomPricingData()
  356. if err != nil {
  357. return nil, err
  358. }
  359. ctx := context.Background()
  360. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  361. if err != nil {
  362. return nil, err
  363. }
  364. q := client.Query(query)
  365. it, err := q.Read(ctx)
  366. if err != nil {
  367. return nil, err
  368. }
  369. var allocations []*OutOfClusterAllocation
  370. for {
  371. var a multiKeyGCPAllocation
  372. err := it.Next(&a)
  373. if err == iterator.Done {
  374. break
  375. }
  376. if err != nil {
  377. return nil, err
  378. }
  379. allocations = append(allocations, multiKeyGCPAllocationToOutOfClusterAllocation(a, aggregators))
  380. }
  381. return allocations, nil
  382. }
  383. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  384. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  385. c, err := gcp.Config.GetCustomPricingData()
  386. if err != nil {
  387. return nil, err
  388. }
  389. ctx := context.Background()
  390. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  391. if err != nil {
  392. return nil, err
  393. }
  394. q := client.Query(query)
  395. it, err := q.Read(ctx)
  396. if err != nil {
  397. return nil, err
  398. }
  399. var allocations []*OutOfClusterAllocation
  400. for {
  401. var a gcpAllocation
  402. err := it.Next(&a)
  403. if err == iterator.Done {
  404. break
  405. }
  406. if err != nil {
  407. return nil, err
  408. }
  409. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  410. }
  411. return allocations, nil
  412. }
  413. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  414. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  415. remote := os.Getenv(remoteEnabled)
  416. remoteEnabled := false
  417. if os.Getenv(remote) == "true" {
  418. remoteEnabled = true
  419. }
  420. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  421. userAgent: "kubecost",
  422. base: http.DefaultTransport,
  423. }})
  424. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  425. if err != nil {
  426. klog.Infof("Error loading metadata cluster-name: %s", err.Error())
  427. }
  428. c, err := gcp.GetConfig()
  429. if err != nil {
  430. klog.V(1).Infof("Error opening config: %s", err.Error())
  431. }
  432. if c.ClusterName != "" {
  433. attribute = c.ClusterName
  434. }
  435. m := make(map[string]string)
  436. m["name"] = attribute
  437. m["provider"] = "GCP"
  438. m["id"] = os.Getenv(clusterIDKey)
  439. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  440. return m, nil
  441. }
  442. // 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.
  443. func (*GCP) GetDisks() ([]byte, error) {
  444. // metadata API setup
  445. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  446. userAgent: "kubecost",
  447. base: http.DefaultTransport,
  448. }})
  449. projID, err := metadataClient.ProjectID()
  450. if err != nil {
  451. return nil, err
  452. }
  453. client, err := google.DefaultClient(oauth2.NoContext,
  454. "https://www.googleapis.com/auth/compute.readonly")
  455. if err != nil {
  456. return nil, err
  457. }
  458. svc, err := compute.New(client)
  459. if err != nil {
  460. return nil, err
  461. }
  462. res, err := svc.Disks.AggregatedList(projID).Do()
  463. if err != nil {
  464. return nil, err
  465. }
  466. return json.Marshal(res)
  467. }
  468. // GCPPricing represents GCP pricing data for a SKU
  469. type GCPPricing struct {
  470. Name string `json:"name"`
  471. SKUID string `json:"skuId"`
  472. Description string `json:"description"`
  473. Category *GCPResourceInfo `json:"category"`
  474. ServiceRegions []string `json:"serviceRegions"`
  475. PricingInfo []*PricingInfo `json:"pricingInfo"`
  476. ServiceProviderName string `json:"serviceProviderName"`
  477. Node *Node `json:"node"`
  478. PV *PV `json:"pv"`
  479. }
  480. // PricingInfo contains metadata about a cost.
  481. type PricingInfo struct {
  482. Summary string `json:"summary"`
  483. PricingExpression *PricingExpression `json:"pricingExpression"`
  484. CurrencyConversionRate int `json:"currencyConversionRate"`
  485. EffectiveTime string `json:""`
  486. }
  487. // PricingExpression contains metadata about a cost.
  488. type PricingExpression struct {
  489. UsageUnit string `json:"usageUnit"`
  490. UsageUnitDescription string `json:"usageUnitDescription"`
  491. BaseUnit string `json:"baseUnit"`
  492. BaseUnitConversionFactor int64 `json:"-"`
  493. DisplayQuantity int `json:"displayQuantity"`
  494. TieredRates []*TieredRates `json:"tieredRates"`
  495. }
  496. // TieredRates contain data about variable pricing.
  497. type TieredRates struct {
  498. StartUsageAmount int `json:"startUsageAmount"`
  499. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  500. }
  501. // UnitPriceInfo contains data about the actual price being charged.
  502. type UnitPriceInfo struct {
  503. CurrencyCode string `json:"currencyCode"`
  504. Units string `json:"units"`
  505. Nanos float64 `json:"nanos"`
  506. }
  507. // GCPResourceInfo contains metadata about the node.
  508. type GCPResourceInfo struct {
  509. ServiceDisplayName string `json:"serviceDisplayName"`
  510. ResourceFamily string `json:"resourceFamily"`
  511. ResourceGroup string `json:"resourceGroup"`
  512. UsageType string `json:"usageType"`
  513. }
  514. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  515. gcpPricingList := make(map[string]*GCPPricing)
  516. var nextPageToken string
  517. dec := json.NewDecoder(r)
  518. for {
  519. t, err := dec.Token()
  520. if err == io.EOF {
  521. break
  522. }
  523. if t == "skus" {
  524. _, err := dec.Token() // consumes [
  525. if err != nil {
  526. return nil, "", err
  527. }
  528. for dec.More() {
  529. product := &GCPPricing{}
  530. err := dec.Decode(&product)
  531. if err != nil {
  532. return nil, "", err
  533. }
  534. usageType := strings.ToLower(product.Category.UsageType)
  535. instanceType := strings.ToLower(product.Category.ResourceGroup)
  536. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  537. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  538. var nanos float64
  539. if len(product.PricingInfo) > 0 {
  540. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  541. } else {
  542. continue
  543. }
  544. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  545. for _, sr := range product.ServiceRegions {
  546. region := sr
  547. candidateKey := region + "," + "ssd"
  548. if _, ok := pvKeys[candidateKey]; ok {
  549. product.PV = &PV{
  550. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  551. }
  552. gcpPricingList[candidateKey] = product
  553. continue
  554. }
  555. }
  556. continue
  557. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  558. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  559. var nanos float64
  560. if len(product.PricingInfo) > 0 {
  561. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  562. } else {
  563. continue
  564. }
  565. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  566. for _, sr := range product.ServiceRegions {
  567. region := sr
  568. candidateKey := region + "," + "pdstandard"
  569. if _, ok := pvKeys[candidateKey]; ok {
  570. product.PV = &PV{
  571. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  572. }
  573. gcpPricingList[candidateKey] = product
  574. continue
  575. }
  576. }
  577. continue
  578. }
  579. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  580. instanceType = "custom"
  581. }
  582. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") {
  583. instanceType = "n2standard"
  584. }
  585. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "COMPUTE OPTIMIZED") {
  586. instanceType = "c2standard"
  587. }
  588. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  589. instanceType = "e2"
  590. }
  591. partialCPUMap := make(map[string]float64)
  592. partialCPUMap["e2micro"] = 0.25
  593. partialCPUMap["e2small"] = 0.5
  594. partialCPUMap["e2medium"] = 1
  595. /*
  596. var partialCPU float64
  597. if strings.ToLower(instanceType) == "f1micro" {
  598. partialCPU = 0.2
  599. } else if strings.ToLower(instanceType) == "g1small" {
  600. partialCPU = 0.5
  601. }
  602. */
  603. var gpuType string
  604. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  605. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  606. if matchnum == 1 {
  607. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  608. klog.V(4).Info("GPU type found: " + gpuType)
  609. }
  610. }
  611. candidateKeys := []string{}
  612. for _, region := range product.ServiceRegions {
  613. if instanceType == "e2" { // this needs to be done to handle a partial cpu mapping
  614. candidateKeys = append(candidateKeys, region+","+"e2micro"+","+usageType)
  615. candidateKeys = append(candidateKeys, region+","+"e2small"+","+usageType)
  616. candidateKeys = append(candidateKeys, region+","+"e2medium"+","+usageType)
  617. candidateKeys = append(candidateKeys, region+","+"e2standard"+","+usageType)
  618. } else {
  619. candidateKey := region + "," + instanceType + "," + usageType
  620. candidateKeys = append(candidateKeys, candidateKey)
  621. }
  622. }
  623. for _, candidateKey := range candidateKeys {
  624. instanceType = strings.Split(candidateKey, ",")[1] // we may have overriden this while generating candidate keys
  625. region := strings.Split(candidateKey, ",")[0]
  626. candidateKeyGPU := candidateKey + ",gpu"
  627. if gpuType != "" {
  628. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  629. var nanos float64
  630. if len(product.PricingInfo) > 0 {
  631. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  632. } else {
  633. continue
  634. }
  635. hourlyPrice := nanos * math.Pow10(-9)
  636. for k, key := range inputKeys {
  637. if key.GPUType() == gpuType+","+usageType {
  638. if region == strings.Split(k, ",")[0] {
  639. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  640. klog.V(4).Infof("PRODUCT DESCRIPTION: %s", product.Description)
  641. matchedKey := key.Features()
  642. if pl, ok := gcpPricingList[matchedKey]; ok {
  643. pl.Node.GPUName = gpuType
  644. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  645. pl.Node.GPU = "1"
  646. } else {
  647. product.Node = &Node{
  648. GPUName: gpuType,
  649. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  650. GPU: "1",
  651. }
  652. gcpPricingList[matchedKey] = product
  653. }
  654. klog.V(3).Infof("Added data for " + matchedKey)
  655. }
  656. }
  657. }
  658. } else {
  659. _, ok := inputKeys[candidateKey]
  660. _, ok2 := inputKeys[candidateKeyGPU]
  661. if ok || ok2 {
  662. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  663. var nanos float64
  664. if len(product.PricingInfo) > 0 {
  665. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  666. } else {
  667. continue
  668. }
  669. hourlyPrice := nanos * math.Pow10(-9)
  670. if hourlyPrice == 0 {
  671. continue
  672. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  673. if instanceType == "custom" {
  674. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  675. }
  676. if _, ok := gcpPricingList[candidateKey]; ok {
  677. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  678. } else {
  679. product = &GCPPricing{}
  680. product.Node = &Node{
  681. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  682. }
  683. partialCPU, pcok := partialCPUMap[instanceType]
  684. if pcok {
  685. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  686. }
  687. product.Node.UsageType = usageType
  688. gcpPricingList[candidateKey] = product
  689. }
  690. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  691. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  692. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  693. } else {
  694. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  695. product = &GCPPricing{}
  696. product.Node = &Node{
  697. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  698. }
  699. partialCPU, pcok := partialCPUMap[instanceType]
  700. if pcok {
  701. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  702. }
  703. product.Node.UsageType = usageType
  704. gcpPricingList[candidateKeyGPU] = product
  705. }
  706. break
  707. } else {
  708. if _, ok := gcpPricingList[candidateKey]; ok {
  709. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  710. } else {
  711. product = &GCPPricing{}
  712. product.Node = &Node{
  713. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  714. }
  715. partialCPU, pcok := partialCPUMap[instanceType]
  716. if pcok {
  717. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  718. }
  719. product.Node.UsageType = usageType
  720. gcpPricingList[candidateKey] = product
  721. }
  722. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  723. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  724. } else {
  725. product = &GCPPricing{}
  726. product.Node = &Node{
  727. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  728. }
  729. partialCPU, pcok := partialCPUMap[instanceType]
  730. if pcok {
  731. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  732. }
  733. product.Node.UsageType = usageType
  734. gcpPricingList[candidateKeyGPU] = product
  735. }
  736. break
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. if t == "nextPageToken" {
  744. pageToken, err := dec.Token()
  745. if err != nil {
  746. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  747. return nil, "", err
  748. }
  749. if pageToken.(string) != "" {
  750. nextPageToken = pageToken.(string)
  751. } else {
  752. nextPageToken = "done"
  753. }
  754. }
  755. }
  756. return gcpPricingList, nextPageToken, nil
  757. }
  758. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  759. var pages []map[string]*GCPPricing
  760. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  761. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  762. var parsePagesHelper func(string) error
  763. parsePagesHelper = func(pageToken string) error {
  764. if pageToken == "done" {
  765. return nil
  766. } else if pageToken != "" {
  767. url = url + "&pageToken=" + pageToken
  768. }
  769. resp, err := http.Get(url)
  770. if err != nil {
  771. return err
  772. }
  773. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  774. if err != nil {
  775. return err
  776. }
  777. pages = append(pages, page)
  778. return parsePagesHelper(token)
  779. }
  780. err := parsePagesHelper("")
  781. if err != nil {
  782. return nil, err
  783. }
  784. returnPages := make(map[string]*GCPPricing)
  785. for _, page := range pages {
  786. for k, v := range page {
  787. if val, ok := returnPages[k]; ok { //keys may need to be merged
  788. if val.Node != nil {
  789. if val.Node.VCPUCost == "" {
  790. val.Node.VCPUCost = v.Node.VCPUCost
  791. }
  792. if val.Node.RAMCost == "" {
  793. val.Node.RAMCost = v.Node.RAMCost
  794. }
  795. if val.Node.GPUCost == "" {
  796. val.Node.GPUCost = v.Node.GPUCost
  797. val.Node.GPU = v.Node.GPU
  798. val.Node.GPUName = v.Node.GPUName
  799. }
  800. }
  801. if val.PV != nil {
  802. if val.PV.Cost == "" {
  803. val.PV.Cost = v.PV.Cost
  804. }
  805. }
  806. } else {
  807. returnPages[k] = v
  808. }
  809. }
  810. }
  811. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  812. for k, v := range returnPages {
  813. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  814. }
  815. return returnPages, err
  816. }
  817. // 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.
  818. func (gcp *GCP) DownloadPricingData() error {
  819. gcp.DownloadPricingDataLock.Lock()
  820. defer gcp.DownloadPricingDataLock.Unlock()
  821. c, err := gcp.Config.GetCustomPricingData()
  822. if err != nil {
  823. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  824. return err
  825. }
  826. gcp.loadGCPAuthSecret()
  827. gcp.BaseCPUPrice = c.CPU
  828. gcp.ProjectID = c.ProjectID
  829. gcp.BillingDataDataset = c.BillingDataDataset
  830. nodeList := gcp.Clientset.GetAllNodes()
  831. inputkeys := make(map[string]Key)
  832. for _, n := range nodeList {
  833. labels := n.GetObjectMeta().GetLabels()
  834. key := gcp.GetKey(labels)
  835. inputkeys[key.Features()] = key
  836. }
  837. pvList := gcp.Clientset.GetAllPersistentVolumes()
  838. storageClasses := gcp.Clientset.GetAllStorageClasses()
  839. storageClassMap := make(map[string]map[string]string)
  840. for _, storageClass := range storageClasses {
  841. params := storageClass.Parameters
  842. storageClassMap[storageClass.ObjectMeta.Name] = params
  843. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  844. storageClassMap["default"] = params
  845. storageClassMap[""] = params
  846. }
  847. }
  848. pvkeys := make(map[string]PVKey)
  849. for _, pv := range pvList {
  850. params, ok := storageClassMap[pv.Spec.StorageClassName]
  851. if !ok {
  852. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  853. continue
  854. }
  855. key := gcp.GetPVKey(pv, params, "")
  856. pvkeys[key.Features()] = key
  857. }
  858. reserved, err := gcp.getReservedInstances()
  859. if err != nil {
  860. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  861. } else {
  862. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  863. gcp.ReservedInstances = reserved
  864. for _, r := range reserved {
  865. klog.V(1).Infof("%s", r)
  866. }
  867. }
  868. pages, err := gcp.parsePages(inputkeys, pvkeys)
  869. if err != nil {
  870. return err
  871. }
  872. gcp.Pricing = pages
  873. return nil
  874. }
  875. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  876. gcp.DownloadPricingDataLock.RLock()
  877. defer gcp.DownloadPricingDataLock.RUnlock()
  878. pricing, ok := gcp.Pricing[pvk.Features()]
  879. if !ok {
  880. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  881. return &PV{}, nil
  882. }
  883. return pricing.PV, nil
  884. }
  885. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  886. func (gcp *GCP) NetworkPricing() (*Network, error) {
  887. cpricing, err := gcp.Config.GetCustomPricingData()
  888. if err != nil {
  889. return nil, err
  890. }
  891. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  892. if err != nil {
  893. return nil, err
  894. }
  895. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  896. if err != nil {
  897. return nil, err
  898. }
  899. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  900. if err != nil {
  901. return nil, err
  902. }
  903. return &Network{
  904. ZoneNetworkEgressCost: znec,
  905. RegionNetworkEgressCost: rnec,
  906. InternetNetworkEgressCost: inec,
  907. }, nil
  908. }
  909. const (
  910. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  911. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  912. GCPReservedInstanceStatusActive string = "ACTIVE"
  913. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  914. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  915. )
  916. type GCPReservedInstancePlan struct {
  917. Name string
  918. CPUCost float64
  919. RAMCost float64
  920. }
  921. type GCPReservedInstance struct {
  922. ReservedRAM int64
  923. ReservedCPU int64
  924. Plan *GCPReservedInstancePlan
  925. StartDate time.Time
  926. EndDate time.Time
  927. Region string
  928. }
  929. func (r *GCPReservedInstance) String() string {
  930. 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())
  931. }
  932. type GCPReservedCounter struct {
  933. RemainingCPU int64
  934. RemainingRAM int64
  935. Instance *GCPReservedInstance
  936. }
  937. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  938. return &GCPReservedCounter{
  939. RemainingCPU: instance.ReservedCPU,
  940. RemainingRAM: instance.ReservedRAM,
  941. Instance: instance,
  942. }
  943. }
  944. // Two available Reservation plans for GCP, 1-year and 3-year
  945. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  946. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  947. Name: GCPReservedInstancePlanOneYear,
  948. CPUCost: 0.019915,
  949. RAMCost: 0.002669,
  950. },
  951. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  952. Name: GCPReservedInstancePlanThreeYear,
  953. CPUCost: 0.014225,
  954. RAMCost: 0.001907,
  955. },
  956. }
  957. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  958. numReserved := len(gcp.ReservedInstances)
  959. // Early return if no reserved instance data loaded
  960. if numReserved == 0 {
  961. klog.V(4).Infof("[Reserved] No Reserved Instances")
  962. return
  963. }
  964. now := time.Now()
  965. counters := make(map[string][]*GCPReservedCounter)
  966. for _, r := range gcp.ReservedInstances {
  967. if now.Before(r.StartDate) || now.After(r.EndDate) {
  968. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  969. continue
  970. }
  971. _, ok := counters[r.Region]
  972. counter := newReservedCounter(r)
  973. if !ok {
  974. counters[r.Region] = []*GCPReservedCounter{counter}
  975. } else {
  976. counters[r.Region] = append(counters[r.Region], counter)
  977. }
  978. }
  979. gcpNodes := make(map[string]*v1.Node)
  980. currentNodes := gcp.Clientset.GetAllNodes()
  981. // Create a node name -> node map
  982. for _, gcpNode := range currentNodes {
  983. gcpNodes[gcpNode.GetName()] = gcpNode
  984. }
  985. // go through all provider nodes using k8s nodes for region
  986. for nodeName, node := range nodes {
  987. // Reset reserved allocation to prevent double allocation
  988. node.Reserved = nil
  989. kNode, ok := gcpNodes[nodeName]
  990. if !ok {
  991. klog.V(4).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  992. continue
  993. }
  994. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  995. if !ok {
  996. klog.V(4).Infof("[Reserved] Could not find node region")
  997. continue
  998. }
  999. reservedCounters, ok := counters[nodeRegion]
  1000. if !ok {
  1001. klog.V(4).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1002. continue
  1003. }
  1004. node.Reserved = &ReservedInstanceData{
  1005. ReservedCPU: 0,
  1006. ReservedRAM: 0,
  1007. }
  1008. for _, reservedCounter := range reservedCounters {
  1009. if reservedCounter.RemainingCPU != 0 {
  1010. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1011. nodeCPU -= node.Reserved.ReservedCPU
  1012. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1013. if reservedCounter.RemainingCPU >= nodeCPU {
  1014. reservedCounter.RemainingCPU -= nodeCPU
  1015. node.Reserved.ReservedCPU += nodeCPU
  1016. } else {
  1017. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1018. reservedCounter.RemainingCPU = 0
  1019. }
  1020. }
  1021. if reservedCounter.RemainingRAM != 0 {
  1022. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1023. nodeRAM := int64(nodeRAMF)
  1024. nodeRAM -= node.Reserved.ReservedRAM
  1025. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1026. if reservedCounter.RemainingRAM >= nodeRAM {
  1027. reservedCounter.RemainingRAM -= nodeRAM
  1028. node.Reserved.ReservedRAM += nodeRAM
  1029. } else {
  1030. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1031. reservedCounter.RemainingRAM = 0
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1038. var results []*GCPReservedInstance
  1039. ctx := context.Background()
  1040. computeService, err := compute.NewService(ctx)
  1041. if err != nil {
  1042. return nil, err
  1043. }
  1044. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1045. if err != nil {
  1046. return nil, err
  1047. }
  1048. for regionKey, commitList := range commitments.Items {
  1049. for _, commit := range commitList.Commitments {
  1050. if commit.Status != GCPReservedInstanceStatusActive {
  1051. continue
  1052. }
  1053. var vcpu int64 = 0
  1054. var ram int64 = 0
  1055. for _, resource := range commit.Resources {
  1056. switch resource.Type {
  1057. case GCPReservedInstanceResourceTypeRAM:
  1058. ram = resource.Amount * 1024 * 1024
  1059. case GCPReservedInstanceResourceTypeCPU:
  1060. vcpu = resource.Amount
  1061. default:
  1062. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  1063. }
  1064. }
  1065. var region string
  1066. regionStr := strings.Split(regionKey, "/")
  1067. if len(regionStr) == 2 {
  1068. region = regionStr[1]
  1069. }
  1070. timeLayout := "2006-01-02T15:04:05Z07:00"
  1071. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1072. if err != nil {
  1073. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  1074. continue
  1075. }
  1076. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1077. if err != nil {
  1078. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  1079. continue
  1080. }
  1081. // Look for a plan based on the name. Default to One Year if it fails
  1082. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1083. if !ok {
  1084. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1085. }
  1086. results = append(results, &GCPReservedInstance{
  1087. Region: region,
  1088. ReservedRAM: ram,
  1089. ReservedCPU: vcpu,
  1090. Plan: plan,
  1091. StartDate: startTime,
  1092. EndDate: endTime,
  1093. })
  1094. }
  1095. }
  1096. return results, nil
  1097. }
  1098. type pvKey struct {
  1099. Labels map[string]string
  1100. StorageClass string
  1101. StorageClassParameters map[string]string
  1102. DefaultRegion string
  1103. }
  1104. func (key *pvKey) GetStorageClass() string {
  1105. return key.StorageClass
  1106. }
  1107. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  1108. return &pvKey{
  1109. Labels: pv.Labels,
  1110. StorageClass: pv.Spec.StorageClassName,
  1111. StorageClassParameters: parameters,
  1112. DefaultRegion: defaultRegion,
  1113. }
  1114. }
  1115. func (key *pvKey) Features() string {
  1116. // TODO: regional cluster pricing.
  1117. storageClass := key.StorageClassParameters["type"]
  1118. if storageClass == "pd-ssd" {
  1119. storageClass = "ssd"
  1120. } else if storageClass == "pd-standard" {
  1121. storageClass = "pdstandard"
  1122. }
  1123. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  1124. }
  1125. type gcpKey struct {
  1126. Labels map[string]string
  1127. }
  1128. func (gcp *GCP) GetKey(labels map[string]string) Key {
  1129. return &gcpKey{
  1130. Labels: labels,
  1131. }
  1132. }
  1133. func (gcp *gcpKey) ID() string {
  1134. return ""
  1135. }
  1136. func (gcp *gcpKey) GPUType() string {
  1137. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1138. var usageType string
  1139. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1140. usageType = "preemptible"
  1141. } else {
  1142. usageType = "ondemand"
  1143. }
  1144. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  1145. return t + "," + usageType
  1146. }
  1147. return ""
  1148. }
  1149. // GetKey maps node labels to information needed to retrieve pricing data
  1150. func (gcp *gcpKey) Features() string {
  1151. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  1152. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1153. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1154. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1155. instanceType = "n2standard"
  1156. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1157. instanceType = "e2standard"
  1158. } else if strings.HasPrefix(instanceType, "custom") {
  1159. instanceType = "custom" // The suffix of custom does not matter
  1160. }
  1161. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  1162. var usageType string
  1163. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1164. usageType = "preemptible"
  1165. } else {
  1166. usageType = "ondemand"
  1167. }
  1168. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1169. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1170. }
  1171. return region + "," + instanceType + "," + usageType
  1172. }
  1173. // AllNodePricing returns the GCP pricing objects stored
  1174. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1175. gcp.DownloadPricingDataLock.RLock()
  1176. defer gcp.DownloadPricingDataLock.RUnlock()
  1177. return gcp.Pricing, nil
  1178. }
  1179. // NodePricing returns GCP pricing data for a single node
  1180. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  1181. gcp.DownloadPricingDataLock.RLock()
  1182. defer gcp.DownloadPricingDataLock.RUnlock()
  1183. if n, ok := gcp.Pricing[key.Features()]; ok {
  1184. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1185. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1186. return n.Node, nil
  1187. }
  1188. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  1189. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1190. }