2
0

provider.go 50 KB

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