provider.go 51 KB

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