gcpprovider.go 45 KB

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