gcpprovider.go 45 KB

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