gcpprovider.go 45 KB

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