provider.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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. if c.ShareTenancyCosts == "" {
  139. c.ShareTenancyCosts = models.DefaultShareTenancyCost
  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.ServiceKeyName = a.ServiceKeyName
  232. c.ServiceKeySecret = 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) getBillingAPIURL(apiKey, currencyCode string) string {
  861. return fmt.Sprintf(BillingAPIURLFmt, apiKey, currencyCode)
  862. }
  863. func (gcp *GCP) parsePages(inputKeys map[string]models.Key, pvKeys map[string]models.PVKey) (map[string]*GCPPricing, error) {
  864. var pages []map[string]*GCPPricing
  865. c, err := gcp.GetConfig()
  866. if err != nil {
  867. return nil, err
  868. }
  869. url := gcp.getBillingAPIURL(gcp.APIKey, c.CurrencyCode)
  870. var parsePagesHelper func(string) error
  871. parsePagesHelper = func(pageToken string) error {
  872. if pageToken == "done" {
  873. return nil
  874. } else if pageToken != "" {
  875. url = url + "&pageToken=" + pageToken
  876. }
  877. resp, err := http.Get(url)
  878. if err != nil {
  879. return err
  880. }
  881. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  882. if err != nil {
  883. return err
  884. }
  885. pages = append(pages, page)
  886. return parsePagesHelper(token)
  887. }
  888. err = parsePagesHelper("")
  889. if err != nil {
  890. return nil, err
  891. }
  892. returnPages := make(map[string]*GCPPricing)
  893. for _, page := range pages {
  894. for k, v := range page {
  895. if val, ok := returnPages[k]; ok { //keys may need to be merged
  896. if val.Node != nil {
  897. if val.Node.VCPUCost == "" {
  898. val.Node.VCPUCost = v.Node.VCPUCost
  899. }
  900. if val.Node.RAMCost == "" {
  901. val.Node.RAMCost = v.Node.RAMCost
  902. }
  903. if val.Node.GPUCost == "" {
  904. val.Node.GPUCost = v.Node.GPUCost
  905. val.Node.GPU = v.Node.GPU
  906. val.Node.GPUName = v.Node.GPUName
  907. }
  908. }
  909. if val.PV != nil {
  910. if val.PV.Cost == "" {
  911. val.PV.Cost = v.PV.Cost
  912. }
  913. }
  914. } else {
  915. returnPages[k] = v
  916. }
  917. }
  918. }
  919. log.Debugf("ALL PAGES: %+v", returnPages)
  920. for k, v := range returnPages {
  921. if v.Node != nil {
  922. log.Debugf("Returned Page: %s : %+v", k, v.Node)
  923. }
  924. if v.PV != nil {
  925. log.Debugf("Returned Page: %s : %+v", k, v.PV)
  926. }
  927. }
  928. return returnPages, err
  929. }
  930. // 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.
  931. func (gcp *GCP) DownloadPricingData() error {
  932. gcp.DownloadPricingDataLock.Lock()
  933. defer gcp.DownloadPricingDataLock.Unlock()
  934. c, err := gcp.Config.GetCustomPricingData()
  935. if err != nil {
  936. log.Errorf("Error downloading default pricing data: %s", err.Error())
  937. return err
  938. }
  939. gcp.loadGCPAuthSecret()
  940. gcp.BaseCPUPrice = c.CPU
  941. gcp.ProjectID = c.ProjectID
  942. gcp.BillingDataDataset = c.BillingDataDataset
  943. nodeList := gcp.Clientset.GetAllNodes()
  944. inputkeys := make(map[string]models.Key)
  945. defaultRegion := "" // Sometimes, PVs may be missing the region label. In that case assume that they are in the same region as the nodes
  946. for _, n := range nodeList {
  947. labels := n.Labels
  948. 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
  949. gcp.clusterManagementPrice = 0.10
  950. gcp.clusterProvisioner = "GKE"
  951. }
  952. r, _ := util.GetRegion(labels)
  953. if r != "" {
  954. defaultRegion = r
  955. }
  956. key := gcp.GetKey(labels, n)
  957. inputkeys[key.Features()] = key
  958. }
  959. pvList := gcp.Clientset.GetAllPersistentVolumes()
  960. storageClasses := gcp.Clientset.GetAllStorageClasses()
  961. storageClassMap := make(map[string]map[string]string)
  962. for _, storageClass := range storageClasses {
  963. params := storageClass.Parameters
  964. storageClassMap[storageClass.Name] = params
  965. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  966. storageClassMap["default"] = params
  967. storageClassMap[""] = params
  968. }
  969. }
  970. pvkeys := make(map[string]models.PVKey)
  971. for _, pv := range pvList {
  972. params, ok := storageClassMap[pv.Spec.StorageClassName]
  973. if !ok {
  974. log.DedupedWarningf(5, "Unable to find params for storageClassName %s", pv.Name)
  975. continue
  976. }
  977. key := gcp.GetPVKey(pv, params, defaultRegion)
  978. pvkeys[key.Features()] = key
  979. }
  980. reserved, err := gcp.getReservedInstances()
  981. if err != nil {
  982. log.Errorf("Failed to lookup reserved instance data: %s", err.Error())
  983. } else {
  984. gcp.ReservedInstances = reserved
  985. if zerolog.GlobalLevel() <= zerolog.DebugLevel {
  986. log.Debugf("Found %d reserved instances", len(reserved))
  987. for _, r := range reserved {
  988. log.Debugf("%s", r)
  989. }
  990. }
  991. }
  992. pages, err := gcp.parsePages(inputkeys, pvkeys)
  993. if err != nil {
  994. return err
  995. }
  996. gcp.Pricing = pages
  997. return nil
  998. }
  999. func (gcp *GCP) GpuPricing(nodeLabels map[string]string) (string, error) {
  1000. return "", nil
  1001. }
  1002. func (gcp *GCP) PVPricing(pvk models.PVKey) (*models.PV, error) {
  1003. gcp.DownloadPricingDataLock.RLock()
  1004. defer gcp.DownloadPricingDataLock.RUnlock()
  1005. pricing, ok := gcp.Pricing[pvk.Features()]
  1006. if !ok {
  1007. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1008. return &models.PV{}, nil
  1009. }
  1010. return pricing.PV, nil
  1011. }
  1012. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  1013. func (gcp *GCP) NetworkPricing() (*models.Network, error) {
  1014. cpricing, err := gcp.Config.GetCustomPricingData()
  1015. if err != nil {
  1016. return nil, err
  1017. }
  1018. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. return &models.Network{
  1031. ZoneNetworkEgressCost: znec,
  1032. RegionNetworkEgressCost: rnec,
  1033. InternetNetworkEgressCost: inec,
  1034. }, nil
  1035. }
  1036. func (gcp *GCP) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1037. fffrc := 0.025
  1038. afrc := 0.010
  1039. lbidc := 0.008
  1040. numForwardingRules := 1.0
  1041. dataIngressGB := 0.0
  1042. var totalCost float64
  1043. if numForwardingRules < 5 {
  1044. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  1045. } else {
  1046. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  1047. }
  1048. return &models.LoadBalancer{
  1049. Cost: totalCost,
  1050. }, nil
  1051. }
  1052. const (
  1053. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  1054. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  1055. GCPReservedInstanceStatusActive string = "ACTIVE"
  1056. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  1057. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  1058. )
  1059. type GCPReservedInstancePlan struct {
  1060. Name string
  1061. CPUCost float64
  1062. RAMCost float64
  1063. }
  1064. type GCPReservedInstance struct {
  1065. ReservedRAM int64
  1066. ReservedCPU int64
  1067. Plan *GCPReservedInstancePlan
  1068. StartDate time.Time
  1069. EndDate time.Time
  1070. Region string
  1071. }
  1072. func (r *GCPReservedInstance) String() string {
  1073. 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())
  1074. }
  1075. type GCPReservedCounter struct {
  1076. RemainingCPU int64
  1077. RemainingRAM int64
  1078. Instance *GCPReservedInstance
  1079. }
  1080. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  1081. return &GCPReservedCounter{
  1082. RemainingCPU: instance.ReservedCPU,
  1083. RemainingRAM: instance.ReservedRAM,
  1084. Instance: instance,
  1085. }
  1086. }
  1087. // Two available Reservation plans for GCP, 1-year and 3-year
  1088. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  1089. GCPReservedInstancePlanOneYear: {
  1090. Name: GCPReservedInstancePlanOneYear,
  1091. CPUCost: 0.019915,
  1092. RAMCost: 0.002669,
  1093. },
  1094. GCPReservedInstancePlanThreeYear: {
  1095. Name: GCPReservedInstancePlanThreeYear,
  1096. CPUCost: 0.014225,
  1097. RAMCost: 0.001907,
  1098. },
  1099. }
  1100. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  1101. numReserved := len(gcp.ReservedInstances)
  1102. // Early return if no reserved instance data loaded
  1103. if numReserved == 0 {
  1104. log.Debug("[Reserved] No Reserved Instances")
  1105. return
  1106. }
  1107. now := time.Now()
  1108. counters := make(map[string][]*GCPReservedCounter)
  1109. for _, r := range gcp.ReservedInstances {
  1110. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1111. log.Infof("[Reserved] Skipped Reserved Instance due to dates")
  1112. continue
  1113. }
  1114. _, ok := counters[r.Region]
  1115. counter := newReservedCounter(r)
  1116. if !ok {
  1117. counters[r.Region] = []*GCPReservedCounter{counter}
  1118. } else {
  1119. counters[r.Region] = append(counters[r.Region], counter)
  1120. }
  1121. }
  1122. gcpNodes := make(map[string]*clustercache.Node)
  1123. currentNodes := gcp.Clientset.GetAllNodes()
  1124. // Create a node name -> node map
  1125. for _, gcpNode := range currentNodes {
  1126. gcpNodes[gcpNode.Name] = gcpNode
  1127. }
  1128. // go through all provider nodes using k8s nodes for region
  1129. for nodeName, node := range nodes {
  1130. // Reset reserved allocation to prevent double allocation
  1131. node.Reserved = nil
  1132. kNode, ok := gcpNodes[nodeName]
  1133. if !ok {
  1134. log.Debugf("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1135. continue
  1136. }
  1137. nodeRegion, ok := util.GetRegion(kNode.Labels)
  1138. if !ok {
  1139. log.Debug("[Reserved] Could not find node region")
  1140. continue
  1141. }
  1142. reservedCounters, ok := counters[nodeRegion]
  1143. if !ok {
  1144. log.Debugf("[Reserved] Could not find counters for region: %s", nodeRegion)
  1145. continue
  1146. }
  1147. node.Reserved = &models.ReservedInstanceData{
  1148. ReservedCPU: 0,
  1149. ReservedRAM: 0,
  1150. }
  1151. for _, reservedCounter := range reservedCounters {
  1152. if reservedCounter.RemainingCPU != 0 {
  1153. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1154. nodeCPU -= node.Reserved.ReservedCPU
  1155. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1156. if reservedCounter.RemainingCPU >= nodeCPU {
  1157. reservedCounter.RemainingCPU -= nodeCPU
  1158. node.Reserved.ReservedCPU += nodeCPU
  1159. } else {
  1160. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1161. reservedCounter.RemainingCPU = 0
  1162. }
  1163. }
  1164. if reservedCounter.RemainingRAM != 0 {
  1165. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1166. nodeRAM := int64(nodeRAMF)
  1167. nodeRAM -= node.Reserved.ReservedRAM
  1168. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1169. if reservedCounter.RemainingRAM >= nodeRAM {
  1170. reservedCounter.RemainingRAM -= nodeRAM
  1171. node.Reserved.ReservedRAM += nodeRAM
  1172. } else {
  1173. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1174. reservedCounter.RemainingRAM = 0
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1181. var results []*GCPReservedInstance
  1182. ctx := context.Background()
  1183. computeService, err := compute.NewService(ctx)
  1184. if err != nil {
  1185. return nil, err
  1186. }
  1187. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1188. if err != nil {
  1189. return nil, err
  1190. }
  1191. for regionKey, commitList := range commitments.Items {
  1192. for _, commit := range commitList.Commitments {
  1193. if commit.Status != GCPReservedInstanceStatusActive {
  1194. continue
  1195. }
  1196. var vcpu int64 = 0
  1197. var ram int64 = 0
  1198. for _, resource := range commit.Resources {
  1199. switch resource.Type {
  1200. case GCPReservedInstanceResourceTypeRAM:
  1201. ram = resource.Amount * 1024 * 1024
  1202. case GCPReservedInstanceResourceTypeCPU:
  1203. vcpu = resource.Amount
  1204. default:
  1205. log.Debugf("Failed to handle resource type: %s", resource.Type)
  1206. }
  1207. }
  1208. var region string
  1209. regionStr := strings.Split(regionKey, "/")
  1210. if len(regionStr) == 2 {
  1211. region = regionStr[1]
  1212. }
  1213. timeLayout := "2006-01-02T15:04:05Z07:00"
  1214. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1215. if err != nil {
  1216. log.Warnf("Failed to parse start date: %s", commit.StartTimestamp)
  1217. continue
  1218. }
  1219. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1220. if err != nil {
  1221. log.Warnf("Failed to parse end date: %s", commit.EndTimestamp)
  1222. continue
  1223. }
  1224. // Look for a plan based on the name. Default to One Year if it fails
  1225. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1226. if !ok {
  1227. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1228. }
  1229. results = append(results, &GCPReservedInstance{
  1230. Region: region,
  1231. ReservedRAM: ram,
  1232. ReservedCPU: vcpu,
  1233. Plan: plan,
  1234. StartDate: startTime,
  1235. EndDate: endTime,
  1236. })
  1237. }
  1238. }
  1239. return results, nil
  1240. }
  1241. type pvKey struct {
  1242. ProviderID string
  1243. Labels map[string]string
  1244. StorageClass string
  1245. StorageClassParameters map[string]string
  1246. DefaultRegion string
  1247. }
  1248. func (key *pvKey) ID() string {
  1249. return key.ProviderID
  1250. }
  1251. func (key *pvKey) GetStorageClass() string {
  1252. return key.StorageClass
  1253. }
  1254. func (gcp *GCP) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  1255. providerID := ""
  1256. if pv.Spec.GCEPersistentDisk != nil {
  1257. providerID = pv.Spec.GCEPersistentDisk.PDName
  1258. }
  1259. return &pvKey{
  1260. ProviderID: providerID,
  1261. Labels: pv.Labels,
  1262. StorageClass: pv.Spec.StorageClassName,
  1263. StorageClassParameters: parameters,
  1264. DefaultRegion: defaultRegion,
  1265. }
  1266. }
  1267. func (key *pvKey) Features() string {
  1268. // TODO: regional cluster pricing.
  1269. storageClass := key.StorageClassParameters["type"]
  1270. if storageClass == "pd-ssd" {
  1271. storageClass = "ssd"
  1272. } else if storageClass == "pd-standard" {
  1273. storageClass = "pdstandard"
  1274. }
  1275. replicationType := ""
  1276. if rt, ok := key.StorageClassParameters["replication-type"]; ok {
  1277. if rt == "regional-pd" {
  1278. replicationType = ",regional"
  1279. }
  1280. }
  1281. region, _ := util.GetRegion(key.Labels)
  1282. if region == "" {
  1283. region = key.DefaultRegion
  1284. }
  1285. return region + "," + storageClass + replicationType
  1286. }
  1287. type gcpKey struct {
  1288. Labels map[string]string
  1289. }
  1290. func (gcp *GCP) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  1291. return &gcpKey{
  1292. Labels: labels,
  1293. }
  1294. }
  1295. func (gcp *gcpKey) ID() string {
  1296. return ""
  1297. }
  1298. func (k *gcpKey) GPUCount() int {
  1299. return 0
  1300. }
  1301. func (gcp *gcpKey) GPUType() string {
  1302. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1303. usageType := getUsageType(gcp.Labels)
  1304. log.Debugf("GPU of type: \"%s\" found", t)
  1305. return t + "," + usageType
  1306. }
  1307. return ""
  1308. }
  1309. func parseGCPInstanceTypeLabel(it string) string {
  1310. var instanceType string
  1311. splitByDash := strings.Split(it, "-")
  1312. // GKE nodes are labeled with the GCP instance type, but users can deploy on GCP
  1313. // with tools like K3s, whose instance type labels will be "k3s". This logic
  1314. // avoids a panic in the slice operation then there are no dashes (-) in the
  1315. // instance type label value.
  1316. if len(splitByDash) < 2 {
  1317. instanceType = "unknown"
  1318. } else {
  1319. instanceType = strings.ToLower(strings.Join(splitByDash[:2], ""))
  1320. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1321. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1322. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1323. instanceType = "n2standard"
  1324. } else if instanceType == "n4highmem" || instanceType == "n4highcpu" {
  1325. instanceType = "n4standard" // N4 variants are priced the same per vCPU and RAM
  1326. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1327. instanceType = "e2standard"
  1328. } else if instanceType == "n2dhighmem" || instanceType == "n2dhighcpu" {
  1329. instanceType = "n2dstandard"
  1330. } else if strings.HasPrefix(instanceType, "custom") {
  1331. instanceType = "custom" // The suffix of custom does not matter
  1332. }
  1333. }
  1334. return instanceType
  1335. }
  1336. // GetKey maps node labels to information needed to retrieve pricing data
  1337. func (gcp *gcpKey) Features() string {
  1338. var instanceType string
  1339. it, _ := util.GetInstanceType(gcp.Labels)
  1340. if it == "" {
  1341. log.DedupedErrorf(1, "Missing or Unknown 'node.kubernetes.io/instance-type' node label")
  1342. instanceType = "unknown"
  1343. } else {
  1344. instanceType = parseGCPInstanceTypeLabel(it)
  1345. }
  1346. r, _ := util.GetRegion(gcp.Labels)
  1347. region := strings.ToLower(r)
  1348. usageType := getUsageType(gcp.Labels)
  1349. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1350. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1351. }
  1352. return region + "," + instanceType + "," + usageType
  1353. }
  1354. // AllNodePricing returns the GCP pricing objects stored
  1355. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1356. gcp.DownloadPricingDataLock.RLock()
  1357. defer gcp.DownloadPricingDataLock.RUnlock()
  1358. return gcp.Pricing, nil
  1359. }
  1360. func (gcp *GCP) getPricing(key models.Key) (*GCPPricing, bool) {
  1361. gcp.DownloadPricingDataLock.RLock()
  1362. defer gcp.DownloadPricingDataLock.RUnlock()
  1363. n, ok := gcp.Pricing[key.Features()]
  1364. return n, ok
  1365. }
  1366. func (gcp *GCP) isValidPricingKey(key models.Key) bool {
  1367. gcp.DownloadPricingDataLock.RLock()
  1368. defer gcp.DownloadPricingDataLock.RUnlock()
  1369. _, ok := gcp.ValidPricingKeys[key.Features()]
  1370. return ok
  1371. }
  1372. // NodePricing returns GCP pricing data for a single node
  1373. func (gcp *GCP) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  1374. meta := models.PricingMetadata{}
  1375. c, err := gcp.Config.GetCustomPricingData()
  1376. if err != nil {
  1377. meta.Warnings = append(meta.Warnings, fmt.Sprintf("failed to detect currency: %s", err))
  1378. } else {
  1379. meta.Currency = c.CurrencyCode
  1380. }
  1381. if n, ok := gcp.getPricing(key); ok {
  1382. log.Debugf("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1383. // Add pricing URL, but redact the key (hence, "***"")
  1384. meta.Source = fmt.Sprintf("Downloaded pricing from %s", gcp.getBillingAPIURL("***", c.CurrencyCode))
  1385. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1386. return n.Node, meta, nil
  1387. } else if ok := gcp.isValidPricingKey(key); ok {
  1388. meta.Warnings = append(meta.Warnings, fmt.Sprintf("No pricing found, but key is valid: %s", key.Features()))
  1389. err := gcp.DownloadPricingData()
  1390. if err != nil {
  1391. log.Warnf("no pricing data found for %s", key.Features())
  1392. meta.Warnings = append(meta.Warnings, "Failed to download pricing data")
  1393. return nil, meta, fmt.Errorf("failed to download pricing data: %w", err)
  1394. }
  1395. if n, ok := gcp.getPricing(key); ok {
  1396. log.Debugf("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1397. // Add pricing URL, but redact the key (hence, "***"")
  1398. meta.Source = fmt.Sprintf("Downloaded pricing from %s", gcp.getBillingAPIURL("***", c.CurrencyCode))
  1399. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1400. return n.Node, meta, nil
  1401. }
  1402. log.Warnf("no pricing data found for %s", key.Features())
  1403. meta.Warnings = append(meta.Warnings, "Failed to find pricing after downloading data, but key is valid")
  1404. return nil, meta, fmt.Errorf("failed to find pricing data: %s", key.Features())
  1405. }
  1406. meta.Warnings = append(meta.Warnings, fmt.Sprintf("No pricing found, and key is not valid: %s", key.Features()))
  1407. return nil, meta, fmt.Errorf("no pricing data found for %s", key.Features())
  1408. }
  1409. func (gcp *GCP) ServiceAccountStatus() *models.ServiceAccountStatus {
  1410. return &models.ServiceAccountStatus{
  1411. Checks: []*models.ServiceAccountCheck{},
  1412. }
  1413. }
  1414. func (gcp *GCP) PricingSourceStatus() map[string]*models.PricingSource {
  1415. return make(map[string]*models.PricingSource)
  1416. }
  1417. func (gcp *GCP) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1418. class := strings.Split(instanceType, "-")[0]
  1419. return 1.0 - ((1.0 - sustainedUseDiscount(class, defaultDiscount, isPreemptible)) * (1.0 - negotiatedDiscount))
  1420. }
  1421. func (gcp *GCP) Regions() []string {
  1422. regionOverrides := env.GetRegionOverrideList()
  1423. if len(regionOverrides) > 0 {
  1424. log.Debugf("Overriding GCP regions with configured region list: %+v", regionOverrides)
  1425. return regionOverrides
  1426. }
  1427. return gcpRegions
  1428. }
  1429. func sustainedUseDiscount(class string, defaultDiscount float64, isPreemptible bool) float64 {
  1430. if isPreemptible {
  1431. return 0.0
  1432. }
  1433. discount := defaultDiscount
  1434. switch class {
  1435. case "e2", "f1", "g1", "n4":
  1436. discount = 0.0
  1437. case "n2", "n2d":
  1438. discount = 0.2
  1439. }
  1440. return discount
  1441. }
  1442. func ParseGCPProjectID(id string) string {
  1443. // gce://guestbook-12345/...
  1444. // => guestbook-12345
  1445. match := gceRegex.FindStringSubmatch(id)
  1446. if len(match) >= 2 {
  1447. return match[1]
  1448. }
  1449. // Return empty string if an account could not be parsed from provided string
  1450. return ""
  1451. }
  1452. func getUsageType(labels map[string]string) string {
  1453. if t, ok := labels[GKEPreemptibleLabel]; ok && t == "true" {
  1454. return "preemptible"
  1455. } else if t, ok := labels[GKESpotLabel]; ok && t == "true" {
  1456. // https://cloud.google.com/kubernetes-engine/docs/concepts/spot-vms
  1457. return "preemptible"
  1458. } else if t, ok := labels[models.KarpenterCapacityTypeLabel]; ok && t == models.KarpenterCapacitySpotTypeValue {
  1459. return "preemptible"
  1460. }
  1461. return "ondemand"
  1462. }
  1463. // PricingSourceSummary returns the pricing source summary for the provider.
  1464. // The summary represents what was _parsed_ from the pricing source, not
  1465. // everything that was _available_ in the pricing source.
  1466. func (gcp *GCP) PricingSourceSummary() interface{} {
  1467. return gcp.Pricing
  1468. }