gcpprovider.go 45 KB

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