2
0

gcpprovider.go 44 KB

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