gcpprovider.go 42 KB

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