2
0

provider.go 51 KB

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