2
0

gcpprovider.go 45 KB

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