gcpprovider.go 41 KB

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