gcpprovider.go 48 KB

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