gcpprovider.go 43 KB

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