gcpprovider.go 48 KB

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