gcpprovider.go 44 KB

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