gcpprovider.go 44 KB

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