gcpprovider.go 45 KB

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