gcpprovider.go 42 KB

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