gcpprovider.go 40 KB

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