gcpprovider.go 41 KB

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