2
0

gcpprovider.go 46 KB

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