gcpprovider.go 46 KB

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