provider.go 51 KB

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