provider.go 51 KB

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