provider.go 51 KB

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