gcpprovider.go 45 KB

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