gcpprovider.go 45 KB

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