provider.go 51 KB

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