provider.go 50 KB

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