gcpprovider.go 41 KB

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