gcpprovider.go 43 KB

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