gcpprovider.go 41 KB

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