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