gcpprovider.go 44 KB

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