provider.go 50 KB

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