gcpprovider.go 41 KB

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