gcpprovider.go 42 KB

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