2
0

gcpprovider.go 40 KB

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