gcpprovider.go 44 KB

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