gcpprovider.go 44 KB

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