gcpprovider.go 44 KB

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