gcpprovider.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. package cloud
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/kubecost/cost-model/pkg/util/timeutil"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "net/http"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "k8s.io/klog"
  16. "cloud.google.com/go/bigquery"
  17. "cloud.google.com/go/compute/metadata"
  18. "github.com/kubecost/cost-model/pkg/clustercache"
  19. "github.com/kubecost/cost-model/pkg/env"
  20. "github.com/kubecost/cost-model/pkg/log"
  21. "github.com/kubecost/cost-model/pkg/util"
  22. "github.com/kubecost/cost-model/pkg/util/json"
  23. "golang.org/x/oauth2"
  24. "golang.org/x/oauth2/google"
  25. compute "google.golang.org/api/compute/v1"
  26. "google.golang.org/api/iterator"
  27. v1 "k8s.io/api/core/v1"
  28. )
  29. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  30. const BigqueryUpdateType = "bigqueryupdate"
  31. type userAgentTransport struct {
  32. userAgent string
  33. base http.RoundTripper
  34. }
  35. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  36. req.Header.Set("User-Agent", t.userAgent)
  37. return t.base.RoundTrip(req)
  38. }
  39. // GCP implements a provider interface for GCP
  40. type GCP struct {
  41. Pricing map[string]*GCPPricing
  42. Clientset clustercache.ClusterCache
  43. APIKey string
  44. BaseCPUPrice string
  45. ProjectID string
  46. BillingDataDataset string
  47. DownloadPricingDataLock sync.RWMutex
  48. ReservedInstances []*GCPReservedInstance
  49. Config *ProviderConfig
  50. serviceKeyProvided bool
  51. ValidPricingKeys map[string]bool
  52. clusterManagementPrice float64
  53. clusterProvisioner string
  54. *CustomProvider
  55. }
  56. type gcpAllocation struct {
  57. Aggregator bigquery.NullString
  58. Environment bigquery.NullString
  59. Service string
  60. Cost float64
  61. }
  62. type multiKeyGCPAllocation struct {
  63. Keys bigquery.NullString
  64. Service string
  65. Cost float64
  66. }
  67. func multiKeyGCPAllocationToOutOfClusterAllocation(gcpAlloc multiKeyGCPAllocation, aggregatorNames []string) *OutOfClusterAllocation {
  68. var keys []map[string]string
  69. var environment string
  70. var usedAggregatorName string
  71. if gcpAlloc.Keys.Valid {
  72. err := json.Unmarshal([]byte(gcpAlloc.Keys.StringVal), &keys)
  73. if err != nil {
  74. klog.Infof("Invalid unmarshaling response from BigQuery filtered query: %s", err.Error())
  75. }
  76. keyloop:
  77. for _, label := range keys {
  78. for _, aggregatorName := range aggregatorNames {
  79. if label["key"] == aggregatorName {
  80. environment = label["value"]
  81. usedAggregatorName = label["key"]
  82. break keyloop
  83. }
  84. }
  85. }
  86. }
  87. return &OutOfClusterAllocation{
  88. Aggregator: usedAggregatorName,
  89. Environment: environment,
  90. Service: gcpAlloc.Service,
  91. Cost: gcpAlloc.Cost,
  92. }
  93. }
  94. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  95. var aggregator string
  96. if gcpAlloc.Aggregator.Valid {
  97. aggregator = gcpAlloc.Aggregator.StringVal
  98. }
  99. var environment string
  100. if gcpAlloc.Environment.Valid {
  101. environment = gcpAlloc.Environment.StringVal
  102. }
  103. return &OutOfClusterAllocation{
  104. Aggregator: aggregator,
  105. Environment: environment,
  106. Service: gcpAlloc.Service,
  107. Cost: gcpAlloc.Cost,
  108. }
  109. }
  110. // GetLocalStorageQuery returns the cost of local storage for the given window. Setting rate=true
  111. // returns hourly spend. Setting used=true only tracks used storage, not total.
  112. func (gcp *GCP) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  113. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  114. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  115. localStorageCost := 0.04
  116. baseMetric := "container_fs_limit_bytes"
  117. if used {
  118. baseMetric = "container_fs_usage_bytes"
  119. }
  120. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  121. fmtCumulativeQuery := `sum(
  122. sum_over_time(%s{device!="tmpfs", id="/"}[%s:1m]%s)
  123. ) by (%s) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  124. fmtMonthlyQuery := `sum(
  125. avg_over_time(%s{device!="tmpfs", id="/"}[%s:1m]%s)
  126. ) by (%s) / 1024 / 1024 / 1024 * %f`
  127. fmtQuery := fmtCumulativeQuery
  128. if rate {
  129. fmtQuery = fmtMonthlyQuery
  130. }
  131. fmtWindow := timeutil.DurationString(window)
  132. return fmt.Sprintf(fmtQuery, baseMetric, fmtWindow, fmtOffset, env.GetPromClusterLabel(), localStorageCost)
  133. }
  134. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  135. c, err := gcp.Config.GetCustomPricingData()
  136. if err != nil {
  137. return nil, err
  138. }
  139. if c.Discount == "" {
  140. c.Discount = "30%"
  141. }
  142. if c.NegotiatedDiscount == "" {
  143. c.NegotiatedDiscount = "0%"
  144. }
  145. if c.CurrencyCode == "" {
  146. c.CurrencyCode = "USD"
  147. }
  148. return c, nil
  149. }
  150. type BigQueryConfig struct {
  151. ProjectID string `json:"projectID"`
  152. BillingDataDataset string `json:"billingDataDataset"`
  153. Key map[string]string `json:"key"`
  154. }
  155. func (gcp *GCP) GetManagementPlatform() (string, error) {
  156. nodes := gcp.Clientset.GetAllNodes()
  157. if len(nodes) > 0 {
  158. n := nodes[0]
  159. version := n.Status.NodeInfo.KubeletVersion
  160. if strings.Contains(version, "gke") {
  161. return "gke", nil
  162. }
  163. }
  164. return "", nil
  165. }
  166. // Attempts to load a GCP auth secret and copy the contents to the key file.
  167. func (*GCP) loadGCPAuthSecret() {
  168. path := env.GetConfigPathWithDefault("/models/")
  169. keyPath := path + "key.json"
  170. keyExists, _ := util.FileExists(keyPath)
  171. if keyExists {
  172. klog.V(1).Infof("GCP Auth Key already exists, no need to load from secret")
  173. return
  174. }
  175. exists, err := util.FileExists(authSecretPath)
  176. if !exists || err != nil {
  177. errMessage := "Secret does not exist"
  178. if err != nil {
  179. errMessage = err.Error()
  180. }
  181. klog.V(4).Infof("[Warning] Failed to load auth secret, or was not mounted: %s", errMessage)
  182. return
  183. }
  184. result, err := ioutil.ReadFile(authSecretPath)
  185. if err != nil {
  186. klog.V(4).Infof("[Warning] Failed to load auth secret, or was not mounted: %s", err.Error())
  187. return
  188. }
  189. err = ioutil.WriteFile(keyPath, result, 0644)
  190. if err != nil {
  191. klog.V(4).Infof("[Warning] Failed to copy auth secret to %s: %s", keyPath, err.Error())
  192. }
  193. }
  194. func (gcp *GCP) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  195. return gcp.Config.UpdateFromMap(a)
  196. }
  197. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  198. return gcp.Config.Update(func(c *CustomPricing) error {
  199. if updateType == BigqueryUpdateType {
  200. a := BigQueryConfig{}
  201. err := json.NewDecoder(r).Decode(&a)
  202. if err != nil {
  203. return err
  204. }
  205. c.ProjectID = a.ProjectID
  206. c.BillingDataDataset = a.BillingDataDataset
  207. if len(a.Key) > 0 {
  208. j, err := json.Marshal(a.Key)
  209. if err != nil {
  210. return err
  211. }
  212. path := env.GetConfigPathWithDefault("/models/")
  213. keyPath := path + "key.json"
  214. err = ioutil.WriteFile(keyPath, j, 0644)
  215. if err != nil {
  216. return err
  217. }
  218. gcp.serviceKeyProvided = true
  219. }
  220. } else if updateType == AthenaInfoUpdateType {
  221. a := AwsAthenaInfo{}
  222. err := json.NewDecoder(r).Decode(&a)
  223. if err != nil {
  224. return err
  225. }
  226. c.AthenaBucketName = a.AthenaBucketName
  227. c.AthenaRegion = a.AthenaRegion
  228. c.AthenaDatabase = a.AthenaDatabase
  229. c.AthenaTable = a.AthenaTable
  230. c.ServiceKeyName = a.ServiceKeyName
  231. c.ServiceKeySecret = a.ServiceKeySecret
  232. c.AthenaProjectID = a.AccountID
  233. } else {
  234. a := make(map[string]interface{})
  235. err := json.NewDecoder(r).Decode(&a)
  236. if err != nil {
  237. return err
  238. }
  239. for k, v := range a {
  240. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  241. vstr, ok := v.(string)
  242. if ok {
  243. err := SetCustomPricingField(c, kUpper, vstr)
  244. if err != nil {
  245. return err
  246. }
  247. } else {
  248. sci := v.(map[string]interface{})
  249. sc := make(map[string]string)
  250. for k, val := range sci {
  251. sc[k] = val.(string)
  252. }
  253. c.SharedCosts = sc //todo: support reflection/multiple map fields
  254. }
  255. }
  256. }
  257. if env.IsRemoteEnabled() {
  258. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  259. if err != nil {
  260. return err
  261. }
  262. }
  263. return nil
  264. })
  265. }
  266. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  267. // "start" and "end" are dates of the format YYYY-MM-DD
  268. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  269. func (gcp *GCP) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  270. if env.LegacyExternalCostsAPIDisabled() {
  271. return nil, fmt.Errorf("Legacy External Allocations API disabled.")
  272. }
  273. c, err := gcp.Config.GetCustomPricingData()
  274. if err != nil {
  275. return nil, err
  276. }
  277. var s []*OutOfClusterAllocation
  278. if c.ServiceKeyName != "" && c.ServiceKeySecret != "" && !crossCluster {
  279. aws, err := NewCrossClusterProvider("aws", "gcp.json", gcp.Clientset)
  280. if err != nil {
  281. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  282. }
  283. awsOOC, err := aws.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  284. if err != nil {
  285. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  286. }
  287. s = append(s, awsOOC...)
  288. }
  289. formattedAggregators := []string{}
  290. for _, a := range aggregators {
  291. formattedAggregators = append(formattedAggregators, strconv.Quote(a))
  292. }
  293. aggregator := strings.Join(formattedAggregators, ",")
  294. var qerr error
  295. if filterType == "kubernetes_" {
  296. // start, end formatted like: "2019-04-20 00:00:00"
  297. /* OLD METHOD: supported getting all data, including unaggregated.
  298. queryString := fmt.Sprintf(`SELECT
  299. service,
  300. labels.key as aggregator,
  301. labels.value as environment,
  302. SUM(cost) as cost
  303. FROM (SELECT
  304. service.description as service,
  305. labels,
  306. cost
  307. FROM %s
  308. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  309. LEFT JOIN UNNEST(labels) as labels
  310. ON labels.key = "%s"
  311. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end, aggregator) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  312. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  313. gcpOOC, err := gcp.QuerySQL(queryString)
  314. s = append(s, gcpOOC...)
  315. qerr = err
  316. */
  317. queryString := `(
  318. SELECT
  319. service.description as service,
  320. TO_JSON_STRING(labels) as keys,
  321. SUM(cost) as cost
  322. FROM` +
  323. fmt.Sprintf(" `%s` ", c.BillingDataDataset) +
  324. fmt.Sprintf(`WHERE EXISTS (SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key IN (%s))
  325. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  326. GROUP BY service, keys
  327. )`, aggregator, start, end)
  328. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  329. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  330. s = append(s, gcpOOC...)
  331. qerr = err
  332. } else {
  333. if filterType == "kubernetes_labels" {
  334. fvs := strings.Split(filterValue, "=")
  335. if len(fvs) == 2 {
  336. // if we are given "app=myapp" then look for label "kubernetes_label_app=myapp"
  337. filterType = fmt.Sprintf("kubernetes_label_%s", fvs[0])
  338. filterValue = fvs[1]
  339. } else {
  340. klog.V(2).Infof("[Warning] illegal kubernetes_labels filterValue: %s", filterValue)
  341. }
  342. }
  343. queryString := `(
  344. SELECT
  345. service.description as service,
  346. TO_JSON_STRING(labels) as keys,
  347. SUM(cost) as cost
  348. FROM` +
  349. fmt.Sprintf(" `%s` ", c.BillingDataDataset) +
  350. fmt.Sprintf(`WHERE EXISTS (SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key IN (%s))
  351. AND EXISTS (SELECT * FROM UNNEST(labels) AS l WHERE l.key = "%s" AND l.value = "%s")
  352. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  353. GROUP BY service, keys
  354. )`, aggregator, filterType, filterValue, start, end)
  355. klog.V(4).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  356. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  357. s = append(s, gcpOOC...)
  358. qerr = err
  359. }
  360. if qerr != nil && gcp.serviceKeyProvided {
  361. klog.Infof("Error querying gcp: %s", qerr)
  362. }
  363. return s, qerr
  364. }
  365. func (gcp *GCP) multiLabelQuery(query string, aggregators []string) ([]*OutOfClusterAllocation, error) {
  366. c, err := gcp.Config.GetCustomPricingData()
  367. if err != nil {
  368. return nil, err
  369. }
  370. ctx := context.Background()
  371. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  372. if err != nil {
  373. return nil, err
  374. }
  375. q := client.Query(query)
  376. it, err := q.Read(ctx)
  377. if err != nil {
  378. return nil, err
  379. }
  380. var allocations []*OutOfClusterAllocation
  381. for {
  382. var a multiKeyGCPAllocation
  383. err := it.Next(&a)
  384. if err == iterator.Done {
  385. break
  386. }
  387. if err != nil {
  388. return nil, err
  389. }
  390. allocations = append(allocations, multiKeyGCPAllocationToOutOfClusterAllocation(a, aggregators))
  391. }
  392. return allocations, nil
  393. }
  394. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  395. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  396. c, err := gcp.Config.GetCustomPricingData()
  397. if err != nil {
  398. return nil, err
  399. }
  400. ctx := context.Background()
  401. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  402. if err != nil {
  403. return nil, err
  404. }
  405. q := client.Query(query)
  406. it, err := q.Read(ctx)
  407. if err != nil {
  408. return nil, err
  409. }
  410. var allocations []*OutOfClusterAllocation
  411. for {
  412. var a gcpAllocation
  413. err := it.Next(&a)
  414. if err == iterator.Done {
  415. break
  416. }
  417. if err != nil {
  418. return nil, err
  419. }
  420. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  421. }
  422. return allocations, nil
  423. }
  424. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  425. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  426. remoteEnabled := env.IsRemoteEnabled()
  427. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  428. userAgent: "kubecost",
  429. base: http.DefaultTransport,
  430. }})
  431. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  432. if err != nil {
  433. klog.Infof("Error loading metadata cluster-name: %s", err.Error())
  434. }
  435. c, err := gcp.GetConfig()
  436. if err != nil {
  437. klog.V(1).Infof("Error opening config: %s", err.Error())
  438. }
  439. if c.ClusterName != "" {
  440. attribute = c.ClusterName
  441. }
  442. m := make(map[string]string)
  443. m["name"] = attribute
  444. m["provider"] = "GCP"
  445. m["provisioner"] = gcp.clusterProvisioner
  446. m["id"] = env.GetClusterID()
  447. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  448. return m, nil
  449. }
  450. func (gcp *GCP) ClusterManagementPricing() (string, float64, error) {
  451. return gcp.clusterProvisioner, gcp.clusterManagementPrice, nil
  452. }
  453. func (*GCP) GetAddresses() ([]byte, error) {
  454. // metadata API setup
  455. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  456. userAgent: "kubecost",
  457. base: http.DefaultTransport,
  458. }})
  459. projID, err := metadataClient.ProjectID()
  460. if err != nil {
  461. return nil, err
  462. }
  463. client, err := google.DefaultClient(oauth2.NoContext,
  464. "https://www.googleapis.com/auth/compute.readonly")
  465. if err != nil {
  466. return nil, err
  467. }
  468. svc, err := compute.New(client)
  469. if err != nil {
  470. return nil, err
  471. }
  472. res, err := svc.Addresses.AggregatedList(projID).Do()
  473. if err != nil {
  474. return nil, err
  475. }
  476. return json.Marshal(res)
  477. }
  478. // 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.
  479. func (*GCP) GetDisks() ([]byte, error) {
  480. // metadata API setup
  481. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  482. userAgent: "kubecost",
  483. base: http.DefaultTransport,
  484. }})
  485. projID, err := metadataClient.ProjectID()
  486. if err != nil {
  487. return nil, err
  488. }
  489. client, err := google.DefaultClient(oauth2.NoContext,
  490. "https://www.googleapis.com/auth/compute.readonly")
  491. if err != nil {
  492. return nil, err
  493. }
  494. svc, err := compute.New(client)
  495. if err != nil {
  496. return nil, err
  497. }
  498. res, err := svc.Disks.AggregatedList(projID).Do()
  499. if err != nil {
  500. return nil, err
  501. }
  502. return json.Marshal(res)
  503. }
  504. // GCPPricing represents GCP pricing data for a SKU
  505. type GCPPricing struct {
  506. Name string `json:"name"`
  507. SKUID string `json:"skuId"`
  508. Description string `json:"description"`
  509. Category *GCPResourceInfo `json:"category"`
  510. ServiceRegions []string `json:"serviceRegions"`
  511. PricingInfo []*PricingInfo `json:"pricingInfo"`
  512. ServiceProviderName string `json:"serviceProviderName"`
  513. Node *Node `json:"node"`
  514. PV *PV `json:"pv"`
  515. }
  516. // PricingInfo contains metadata about a cost.
  517. type PricingInfo struct {
  518. Summary string `json:"summary"`
  519. PricingExpression *PricingExpression `json:"pricingExpression"`
  520. CurrencyConversionRate float64 `json:"currencyConversionRate"`
  521. EffectiveTime string `json:""`
  522. }
  523. // PricingExpression contains metadata about a cost.
  524. type PricingExpression struct {
  525. UsageUnit string `json:"usageUnit"`
  526. UsageUnitDescription string `json:"usageUnitDescription"`
  527. BaseUnit string `json:"baseUnit"`
  528. BaseUnitConversionFactor int64 `json:"-"`
  529. DisplayQuantity int `json:"displayQuantity"`
  530. TieredRates []*TieredRates `json:"tieredRates"`
  531. }
  532. // TieredRates contain data about variable pricing.
  533. type TieredRates struct {
  534. StartUsageAmount int `json:"startUsageAmount"`
  535. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  536. }
  537. // UnitPriceInfo contains data about the actual price being charged.
  538. type UnitPriceInfo struct {
  539. CurrencyCode string `json:"currencyCode"`
  540. Units string `json:"units"`
  541. Nanos float64 `json:"nanos"`
  542. }
  543. // GCPResourceInfo contains metadata about the node.
  544. type GCPResourceInfo struct {
  545. ServiceDisplayName string `json:"serviceDisplayName"`
  546. ResourceFamily string `json:"resourceFamily"`
  547. ResourceGroup string `json:"resourceGroup"`
  548. UsageType string `json:"usageType"`
  549. }
  550. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  551. gcpPricingList := make(map[string]*GCPPricing)
  552. var nextPageToken string
  553. dec := json.NewDecoder(r)
  554. for {
  555. t, err := dec.Token()
  556. if err == io.EOF {
  557. break
  558. }
  559. if t == "skus" {
  560. _, err := dec.Token() // consumes [
  561. if err != nil {
  562. return nil, "", err
  563. }
  564. for dec.More() {
  565. product := &GCPPricing{}
  566. err := dec.Decode(&product)
  567. if err != nil {
  568. return nil, "", err
  569. }
  570. usageType := strings.ToLower(product.Category.UsageType)
  571. instanceType := strings.ToLower(product.Category.ResourceGroup)
  572. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  573. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  574. var nanos float64
  575. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  576. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  577. } else {
  578. continue
  579. }
  580. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  581. for _, sr := range product.ServiceRegions {
  582. region := sr
  583. candidateKey := region + "," + "ssd"
  584. if _, ok := pvKeys[candidateKey]; ok {
  585. product.PV = &PV{
  586. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  587. }
  588. gcpPricingList[candidateKey] = product
  589. continue
  590. }
  591. }
  592. continue
  593. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  594. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  595. var nanos float64
  596. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  597. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  598. } else {
  599. continue
  600. }
  601. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  602. for _, sr := range product.ServiceRegions {
  603. region := sr
  604. candidateKey := region + "," + "pdstandard"
  605. if _, ok := pvKeys[candidateKey]; ok {
  606. product.PV = &PV{
  607. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  608. }
  609. gcpPricingList[candidateKey] = product
  610. continue
  611. }
  612. }
  613. continue
  614. }
  615. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  616. instanceType = "custom"
  617. }
  618. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") && !strings.Contains(strings.ToUpper(product.Description), "PREMIUM") {
  619. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2D AMD") {
  620. instanceType = "n2dstandard"
  621. } else {
  622. instanceType = "n2standard"
  623. }
  624. }
  625. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "COMPUTE OPTIMIZED") {
  626. instanceType = "c2standard"
  627. }
  628. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  629. instanceType = "e2"
  630. }
  631. partialCPUMap := make(map[string]float64)
  632. partialCPUMap["e2micro"] = 0.25
  633. partialCPUMap["e2small"] = 0.5
  634. partialCPUMap["e2medium"] = 1
  635. /*
  636. var partialCPU float64
  637. if strings.ToLower(instanceType) == "f1micro" {
  638. partialCPU = 0.2
  639. } else if strings.ToLower(instanceType) == "g1small" {
  640. partialCPU = 0.5
  641. }
  642. */
  643. var gpuType string
  644. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  645. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  646. if matchnum == 1 {
  647. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  648. klog.V(4).Info("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. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  686. klog.V(4).Infof("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. klog.V(3).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. klog.V(4).Infof("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. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  738. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  739. } else {
  740. klog.V(1).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. klog.V(2).Infof("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. klog.V(2).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. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  862. for k, v := range returnPages {
  863. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  864. }
  865. return returnPages, err
  866. }
  867. // 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.
  868. func (gcp *GCP) DownloadPricingData() error {
  869. gcp.DownloadPricingDataLock.Lock()
  870. defer gcp.DownloadPricingDataLock.Unlock()
  871. c, err := gcp.Config.GetCustomPricingData()
  872. if err != nil {
  873. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  874. return err
  875. }
  876. gcp.loadGCPAuthSecret()
  877. gcp.BaseCPUPrice = c.CPU
  878. gcp.ProjectID = c.ProjectID
  879. gcp.BillingDataDataset = c.BillingDataDataset
  880. nodeList := gcp.Clientset.GetAllNodes()
  881. inputkeys := make(map[string]Key)
  882. for _, n := range nodeList {
  883. labels := n.GetObjectMeta().GetLabels()
  884. 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
  885. gcp.clusterManagementPrice = 0.10
  886. gcp.clusterProvisioner = "GKE"
  887. }
  888. key := gcp.GetKey(labels, n)
  889. inputkeys[key.Features()] = key
  890. }
  891. pvList := gcp.Clientset.GetAllPersistentVolumes()
  892. storageClasses := gcp.Clientset.GetAllStorageClasses()
  893. storageClassMap := make(map[string]map[string]string)
  894. for _, storageClass := range storageClasses {
  895. params := storageClass.Parameters
  896. storageClassMap[storageClass.ObjectMeta.Name] = params
  897. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  898. storageClassMap["default"] = params
  899. storageClassMap[""] = params
  900. }
  901. }
  902. pvkeys := make(map[string]PVKey)
  903. for _, pv := range pvList {
  904. params, ok := storageClassMap[pv.Spec.StorageClassName]
  905. if !ok {
  906. log.DedupedWarningf(5, "Unable to find params for storageClassName %s", pv.Name)
  907. continue
  908. }
  909. key := gcp.GetPVKey(pv, params, "")
  910. pvkeys[key.Features()] = key
  911. }
  912. reserved, err := gcp.getReservedInstances()
  913. if err != nil {
  914. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  915. } else {
  916. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  917. gcp.ReservedInstances = reserved
  918. for _, r := range reserved {
  919. klog.V(1).Infof("%s", r)
  920. }
  921. }
  922. pages, err := gcp.parsePages(inputkeys, pvkeys)
  923. if err != nil {
  924. return err
  925. }
  926. gcp.Pricing = pages
  927. return nil
  928. }
  929. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  930. gcp.DownloadPricingDataLock.RLock()
  931. defer gcp.DownloadPricingDataLock.RUnlock()
  932. pricing, ok := gcp.Pricing[pvk.Features()]
  933. if !ok {
  934. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  935. return &PV{}, nil
  936. }
  937. return pricing.PV, nil
  938. }
  939. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  940. func (gcp *GCP) NetworkPricing() (*Network, error) {
  941. cpricing, err := gcp.Config.GetCustomPricingData()
  942. if err != nil {
  943. return nil, err
  944. }
  945. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  946. if err != nil {
  947. return nil, err
  948. }
  949. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  950. if err != nil {
  951. return nil, err
  952. }
  953. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  954. if err != nil {
  955. return nil, err
  956. }
  957. return &Network{
  958. ZoneNetworkEgressCost: znec,
  959. RegionNetworkEgressCost: rnec,
  960. InternetNetworkEgressCost: inec,
  961. }, nil
  962. }
  963. func (gcp *GCP) LoadBalancerPricing() (*LoadBalancer, error) {
  964. fffrc := 0.025
  965. afrc := 0.010
  966. lbidc := 0.008
  967. numForwardingRules := 1.0
  968. dataIngressGB := 0.0
  969. var totalCost float64
  970. if numForwardingRules < 5 {
  971. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  972. } else {
  973. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  974. }
  975. return &LoadBalancer{
  976. Cost: totalCost,
  977. }, nil
  978. }
  979. const (
  980. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  981. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  982. GCPReservedInstanceStatusActive string = "ACTIVE"
  983. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  984. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  985. )
  986. type GCPReservedInstancePlan struct {
  987. Name string
  988. CPUCost float64
  989. RAMCost float64
  990. }
  991. type GCPReservedInstance struct {
  992. ReservedRAM int64
  993. ReservedCPU int64
  994. Plan *GCPReservedInstancePlan
  995. StartDate time.Time
  996. EndDate time.Time
  997. Region string
  998. }
  999. func (r *GCPReservedInstance) String() string {
  1000. 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())
  1001. }
  1002. type GCPReservedCounter struct {
  1003. RemainingCPU int64
  1004. RemainingRAM int64
  1005. Instance *GCPReservedInstance
  1006. }
  1007. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  1008. return &GCPReservedCounter{
  1009. RemainingCPU: instance.ReservedCPU,
  1010. RemainingRAM: instance.ReservedRAM,
  1011. Instance: instance,
  1012. }
  1013. }
  1014. // Two available Reservation plans for GCP, 1-year and 3-year
  1015. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  1016. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  1017. Name: GCPReservedInstancePlanOneYear,
  1018. CPUCost: 0.019915,
  1019. RAMCost: 0.002669,
  1020. },
  1021. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  1022. Name: GCPReservedInstancePlanThreeYear,
  1023. CPUCost: 0.014225,
  1024. RAMCost: 0.001907,
  1025. },
  1026. }
  1027. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1028. numReserved := len(gcp.ReservedInstances)
  1029. // Early return if no reserved instance data loaded
  1030. if numReserved == 0 {
  1031. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1032. return
  1033. }
  1034. now := time.Now()
  1035. counters := make(map[string][]*GCPReservedCounter)
  1036. for _, r := range gcp.ReservedInstances {
  1037. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1038. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1039. continue
  1040. }
  1041. _, ok := counters[r.Region]
  1042. counter := newReservedCounter(r)
  1043. if !ok {
  1044. counters[r.Region] = []*GCPReservedCounter{counter}
  1045. } else {
  1046. counters[r.Region] = append(counters[r.Region], counter)
  1047. }
  1048. }
  1049. gcpNodes := make(map[string]*v1.Node)
  1050. currentNodes := gcp.Clientset.GetAllNodes()
  1051. // Create a node name -> node map
  1052. for _, gcpNode := range currentNodes {
  1053. gcpNodes[gcpNode.GetName()] = gcpNode
  1054. }
  1055. // go through all provider nodes using k8s nodes for region
  1056. for nodeName, node := range nodes {
  1057. // Reset reserved allocation to prevent double allocation
  1058. node.Reserved = nil
  1059. kNode, ok := gcpNodes[nodeName]
  1060. if !ok {
  1061. klog.V(4).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1062. continue
  1063. }
  1064. nodeRegion, ok := util.GetRegion(kNode.Labels)
  1065. if !ok {
  1066. klog.V(4).Infof("[Reserved] Could not find node region")
  1067. continue
  1068. }
  1069. reservedCounters, ok := counters[nodeRegion]
  1070. if !ok {
  1071. klog.V(4).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1072. continue
  1073. }
  1074. node.Reserved = &ReservedInstanceData{
  1075. ReservedCPU: 0,
  1076. ReservedRAM: 0,
  1077. }
  1078. for _, reservedCounter := range reservedCounters {
  1079. if reservedCounter.RemainingCPU != 0 {
  1080. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1081. nodeCPU -= node.Reserved.ReservedCPU
  1082. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1083. if reservedCounter.RemainingCPU >= nodeCPU {
  1084. reservedCounter.RemainingCPU -= nodeCPU
  1085. node.Reserved.ReservedCPU += nodeCPU
  1086. } else {
  1087. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1088. reservedCounter.RemainingCPU = 0
  1089. }
  1090. }
  1091. if reservedCounter.RemainingRAM != 0 {
  1092. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1093. nodeRAM := int64(nodeRAMF)
  1094. nodeRAM -= node.Reserved.ReservedRAM
  1095. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1096. if reservedCounter.RemainingRAM >= nodeRAM {
  1097. reservedCounter.RemainingRAM -= nodeRAM
  1098. node.Reserved.ReservedRAM += nodeRAM
  1099. } else {
  1100. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1101. reservedCounter.RemainingRAM = 0
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1108. var results []*GCPReservedInstance
  1109. ctx := context.Background()
  1110. computeService, err := compute.NewService(ctx)
  1111. if err != nil {
  1112. return nil, err
  1113. }
  1114. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1115. if err != nil {
  1116. return nil, err
  1117. }
  1118. for regionKey, commitList := range commitments.Items {
  1119. for _, commit := range commitList.Commitments {
  1120. if commit.Status != GCPReservedInstanceStatusActive {
  1121. continue
  1122. }
  1123. var vcpu int64 = 0
  1124. var ram int64 = 0
  1125. for _, resource := range commit.Resources {
  1126. switch resource.Type {
  1127. case GCPReservedInstanceResourceTypeRAM:
  1128. ram = resource.Amount * 1024 * 1024
  1129. case GCPReservedInstanceResourceTypeCPU:
  1130. vcpu = resource.Amount
  1131. default:
  1132. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  1133. }
  1134. }
  1135. var region string
  1136. regionStr := strings.Split(regionKey, "/")
  1137. if len(regionStr) == 2 {
  1138. region = regionStr[1]
  1139. }
  1140. timeLayout := "2006-01-02T15:04:05Z07:00"
  1141. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1142. if err != nil {
  1143. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  1144. continue
  1145. }
  1146. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1147. if err != nil {
  1148. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  1149. continue
  1150. }
  1151. // Look for a plan based on the name. Default to One Year if it fails
  1152. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1153. if !ok {
  1154. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1155. }
  1156. results = append(results, &GCPReservedInstance{
  1157. Region: region,
  1158. ReservedRAM: ram,
  1159. ReservedCPU: vcpu,
  1160. Plan: plan,
  1161. StartDate: startTime,
  1162. EndDate: endTime,
  1163. })
  1164. }
  1165. }
  1166. return results, nil
  1167. }
  1168. type pvKey struct {
  1169. Labels map[string]string
  1170. StorageClass string
  1171. StorageClassParameters map[string]string
  1172. DefaultRegion string
  1173. }
  1174. func (key *pvKey) ID() string {
  1175. return ""
  1176. }
  1177. func (key *pvKey) GetStorageClass() string {
  1178. return key.StorageClass
  1179. }
  1180. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  1181. return &pvKey{
  1182. Labels: pv.Labels,
  1183. StorageClass: pv.Spec.StorageClassName,
  1184. StorageClassParameters: parameters,
  1185. DefaultRegion: defaultRegion,
  1186. }
  1187. }
  1188. func (key *pvKey) Features() string {
  1189. // TODO: regional cluster pricing.
  1190. storageClass := key.StorageClassParameters["type"]
  1191. if storageClass == "pd-ssd" {
  1192. storageClass = "ssd"
  1193. } else if storageClass == "pd-standard" {
  1194. storageClass = "pdstandard"
  1195. }
  1196. region, _ := util.GetRegion(key.Labels)
  1197. return region + "," + storageClass
  1198. }
  1199. type gcpKey struct {
  1200. Labels map[string]string
  1201. }
  1202. func (gcp *GCP) GetKey(labels map[string]string, n *v1.Node) Key {
  1203. return &gcpKey{
  1204. Labels: labels,
  1205. }
  1206. }
  1207. func (gcp *gcpKey) ID() string {
  1208. return ""
  1209. }
  1210. func (gcp *gcpKey) GPUType() string {
  1211. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1212. var usageType string
  1213. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1214. usageType = "preemptible"
  1215. } else {
  1216. usageType = "ondemand"
  1217. }
  1218. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  1219. return t + "," + usageType
  1220. }
  1221. return ""
  1222. }
  1223. // GetKey maps node labels to information needed to retrieve pricing data
  1224. func (gcp *gcpKey) Features() string {
  1225. var instanceType string
  1226. it, _ := util.GetInstanceType(gcp.Labels)
  1227. if it == "" {
  1228. log.DedupedErrorf(1, "Missing or Unknown 'node.kubernetes.io/instance-type' node label")
  1229. instanceType = "unknown"
  1230. } else {
  1231. instanceType = strings.ToLower(strings.Join(strings.Split(it, "-")[:2], ""))
  1232. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1233. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1234. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1235. instanceType = "n2standard"
  1236. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1237. instanceType = "e2standard"
  1238. } else if strings.HasPrefix(instanceType, "custom") {
  1239. instanceType = "custom" // The suffix of custom does not matter
  1240. }
  1241. }
  1242. r, _ := util.GetRegion(gcp.Labels)
  1243. region := strings.ToLower(r)
  1244. var usageType string
  1245. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1246. usageType = "preemptible"
  1247. } else {
  1248. usageType = "ondemand"
  1249. }
  1250. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1251. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1252. }
  1253. return region + "," + instanceType + "," + usageType
  1254. }
  1255. // AllNodePricing returns the GCP pricing objects stored
  1256. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1257. gcp.DownloadPricingDataLock.RLock()
  1258. defer gcp.DownloadPricingDataLock.RUnlock()
  1259. return gcp.Pricing, nil
  1260. }
  1261. func (gcp *GCP) getPricing(key Key) (*GCPPricing, bool) {
  1262. gcp.DownloadPricingDataLock.RLock()
  1263. defer gcp.DownloadPricingDataLock.RUnlock()
  1264. n, ok := gcp.Pricing[key.Features()]
  1265. return n, ok
  1266. }
  1267. func (gcp *GCP) isValidPricingKey(key Key) bool {
  1268. gcp.DownloadPricingDataLock.RLock()
  1269. defer gcp.DownloadPricingDataLock.RUnlock()
  1270. _, ok := gcp.ValidPricingKeys[key.Features()]
  1271. return ok
  1272. }
  1273. // NodePricing returns GCP pricing data for a single node
  1274. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  1275. if n, ok := gcp.getPricing(key); ok {
  1276. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1277. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1278. return n.Node, nil
  1279. } else if ok := gcp.isValidPricingKey(key); ok {
  1280. err := gcp.DownloadPricingData()
  1281. if err != nil {
  1282. return nil, fmt.Errorf("Download pricing data failed: %s", err.Error())
  1283. }
  1284. if n, ok := gcp.getPricing(key); ok {
  1285. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1286. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1287. return n.Node, nil
  1288. }
  1289. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  1290. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1291. }
  1292. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1293. }
  1294. func (gcp *GCP) ServiceAccountStatus() *ServiceAccountStatus {
  1295. return &ServiceAccountStatus{
  1296. Checks: []*ServiceAccountCheck{},
  1297. }
  1298. }
  1299. func (gcp *GCP) PricingSourceStatus() map[string]*PricingSource {
  1300. return make(map[string]*PricingSource)
  1301. }
  1302. func (gcp *GCP) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1303. class := strings.Split(instanceType, "-")[0]
  1304. return 1.0 - ((1.0 - sustainedUseDiscount(class, defaultDiscount, isPreemptible)) * (1.0 - negotiatedDiscount))
  1305. }
  1306. func sustainedUseDiscount(class string, defaultDiscount float64, isPreemptible bool) float64 {
  1307. if isPreemptible {
  1308. return 0.0
  1309. }
  1310. discount := defaultDiscount
  1311. switch class {
  1312. case "e2", "f1", "g1":
  1313. discount = 0.0
  1314. case "n2", "n2d":
  1315. discount = 0.2
  1316. }
  1317. return discount
  1318. }