gcpprovider.go 41 KB

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