provider.go 48 KB

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