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