gcpprovider.go 40 KB

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