gcpprovider.go 41 KB

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