gcpprovider.go 41 KB

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