gcpprovider.go 41 KB

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