gcpprovider.go 39 KB

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