gcpprovider.go 44 KB

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