provider.go 51 KB

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