provider.go 51 KB

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