gcpprovider.go 44 KB

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