provider.go 50 KB

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