provider.go 50 KB

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