gcpprovider.go 48 KB

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