gcpprovider.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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. candidateKeys = append(candidateKeys, region+","+"e2custom"+","+usageType)
  658. } else {
  659. candidateKey := region + "," + instanceType + "," + usageType
  660. candidateKeys = append(candidateKeys, candidateKey)
  661. }
  662. }
  663. for _, candidateKey := range candidateKeys {
  664. instanceType = strings.Split(candidateKey, ",")[1] // we may have overriden this while generating candidate keys
  665. region := strings.Split(candidateKey, ",")[0]
  666. candidateKeyGPU := candidateKey + ",gpu"
  667. gcp.ValidPricingKeys[candidateKey] = true
  668. gcp.ValidPricingKeys[candidateKeyGPU] = true
  669. if gpuType != "" {
  670. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  671. var nanos float64
  672. if len(product.PricingInfo) > 0 {
  673. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  674. } else {
  675. continue
  676. }
  677. hourlyPrice := nanos * math.Pow10(-9)
  678. for k, key := range inputKeys {
  679. if key.GPUType() == gpuType+","+usageType {
  680. if region == strings.Split(k, ",")[0] {
  681. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  682. klog.V(4).Infof("PRODUCT DESCRIPTION: %s", product.Description)
  683. matchedKey := key.Features()
  684. if pl, ok := gcpPricingList[matchedKey]; ok {
  685. pl.Node.GPUName = gpuType
  686. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  687. pl.Node.GPU = "1"
  688. } else {
  689. product.Node = &Node{
  690. GPUName: gpuType,
  691. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  692. GPU: "1",
  693. }
  694. gcpPricingList[matchedKey] = product
  695. }
  696. klog.V(3).Infof("Added data for " + matchedKey)
  697. }
  698. }
  699. }
  700. } else {
  701. _, ok := inputKeys[candidateKey]
  702. _, ok2 := inputKeys[candidateKeyGPU]
  703. if ok || ok2 {
  704. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  705. var nanos float64
  706. if len(product.PricingInfo) > 0 {
  707. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  708. } else {
  709. continue
  710. }
  711. hourlyPrice := nanos * math.Pow10(-9)
  712. if hourlyPrice == 0 {
  713. continue
  714. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  715. if instanceType == "custom" {
  716. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  717. }
  718. if _, ok := gcpPricingList[candidateKey]; ok {
  719. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  720. } else {
  721. product = &GCPPricing{}
  722. product.Node = &Node{
  723. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  724. }
  725. partialCPU, pcok := partialCPUMap[instanceType]
  726. if pcok {
  727. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  728. }
  729. product.Node.UsageType = usageType
  730. gcpPricingList[candidateKey] = product
  731. }
  732. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  733. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  734. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  735. } else {
  736. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  737. product = &GCPPricing{}
  738. product.Node = &Node{
  739. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  740. }
  741. partialCPU, pcok := partialCPUMap[instanceType]
  742. if pcok {
  743. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  744. }
  745. product.Node.UsageType = usageType
  746. gcpPricingList[candidateKeyGPU] = product
  747. }
  748. break
  749. } else {
  750. if _, ok := gcpPricingList[candidateKey]; ok {
  751. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  752. } else {
  753. product = &GCPPricing{}
  754. product.Node = &Node{
  755. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  756. }
  757. partialCPU, pcok := partialCPUMap[instanceType]
  758. if pcok {
  759. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  760. }
  761. product.Node.UsageType = usageType
  762. gcpPricingList[candidateKey] = product
  763. }
  764. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  765. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  766. } else {
  767. product = &GCPPricing{}
  768. product.Node = &Node{
  769. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  770. }
  771. partialCPU, pcok := partialCPUMap[instanceType]
  772. if pcok {
  773. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  774. }
  775. product.Node.UsageType = usageType
  776. gcpPricingList[candidateKeyGPU] = product
  777. }
  778. break
  779. }
  780. }
  781. }
  782. }
  783. }
  784. }
  785. if t == "nextPageToken" {
  786. pageToken, err := dec.Token()
  787. if err != nil {
  788. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  789. return nil, "", err
  790. }
  791. if pageToken.(string) != "" {
  792. nextPageToken = pageToken.(string)
  793. } else {
  794. nextPageToken = "done"
  795. }
  796. }
  797. }
  798. return gcpPricingList, nextPageToken, nil
  799. }
  800. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  801. var pages []map[string]*GCPPricing
  802. c, err := gcp.GetConfig()
  803. if err != nil {
  804. return nil, err
  805. }
  806. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey + "&currencyCode=" + c.CurrencyCode
  807. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  808. var parsePagesHelper func(string) error
  809. parsePagesHelper = func(pageToken string) error {
  810. if pageToken == "done" {
  811. return nil
  812. } else if pageToken != "" {
  813. url = url + "&pageToken=" + pageToken
  814. }
  815. resp, err := http.Get(url)
  816. if err != nil {
  817. return err
  818. }
  819. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  820. if err != nil {
  821. return err
  822. }
  823. pages = append(pages, page)
  824. return parsePagesHelper(token)
  825. }
  826. err = parsePagesHelper("")
  827. if err != nil {
  828. return nil, err
  829. }
  830. returnPages := make(map[string]*GCPPricing)
  831. for _, page := range pages {
  832. for k, v := range page {
  833. if val, ok := returnPages[k]; ok { //keys may need to be merged
  834. if val.Node != nil {
  835. if val.Node.VCPUCost == "" {
  836. val.Node.VCPUCost = v.Node.VCPUCost
  837. }
  838. if val.Node.RAMCost == "" {
  839. val.Node.RAMCost = v.Node.RAMCost
  840. }
  841. if val.Node.GPUCost == "" {
  842. val.Node.GPUCost = v.Node.GPUCost
  843. val.Node.GPU = v.Node.GPU
  844. val.Node.GPUName = v.Node.GPUName
  845. }
  846. }
  847. if val.PV != nil {
  848. if val.PV.Cost == "" {
  849. val.PV.Cost = v.PV.Cost
  850. }
  851. }
  852. } else {
  853. returnPages[k] = v
  854. }
  855. }
  856. }
  857. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  858. for k, v := range returnPages {
  859. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  860. }
  861. return returnPages, err
  862. }
  863. // 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.
  864. func (gcp *GCP) DownloadPricingData() error {
  865. gcp.DownloadPricingDataLock.Lock()
  866. defer gcp.DownloadPricingDataLock.Unlock()
  867. c, err := gcp.Config.GetCustomPricingData()
  868. if err != nil {
  869. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  870. return err
  871. }
  872. gcp.loadGCPAuthSecret()
  873. gcp.BaseCPUPrice = c.CPU
  874. gcp.ProjectID = c.ProjectID
  875. gcp.BillingDataDataset = c.BillingDataDataset
  876. nodeList := gcp.Clientset.GetAllNodes()
  877. inputkeys := make(map[string]Key)
  878. for _, n := range nodeList {
  879. labels := n.GetObjectMeta().GetLabels()
  880. 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
  881. gcp.clusterManagementPrice = 0.10
  882. gcp.clusterProvisioner = "GKE"
  883. }
  884. key := gcp.GetKey(labels, n)
  885. inputkeys[key.Features()] = key
  886. }
  887. pvList := gcp.Clientset.GetAllPersistentVolumes()
  888. storageClasses := gcp.Clientset.GetAllStorageClasses()
  889. storageClassMap := make(map[string]map[string]string)
  890. for _, storageClass := range storageClasses {
  891. params := storageClass.Parameters
  892. storageClassMap[storageClass.ObjectMeta.Name] = params
  893. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  894. storageClassMap["default"] = params
  895. storageClassMap[""] = params
  896. }
  897. }
  898. pvkeys := make(map[string]PVKey)
  899. for _, pv := range pvList {
  900. params, ok := storageClassMap[pv.Spec.StorageClassName]
  901. if !ok {
  902. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  903. continue
  904. }
  905. key := gcp.GetPVKey(pv, params, "")
  906. pvkeys[key.Features()] = key
  907. }
  908. reserved, err := gcp.getReservedInstances()
  909. if err != nil {
  910. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  911. } else {
  912. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  913. gcp.ReservedInstances = reserved
  914. for _, r := range reserved {
  915. klog.V(1).Infof("%s", r)
  916. }
  917. }
  918. pages, err := gcp.parsePages(inputkeys, pvkeys)
  919. if err != nil {
  920. return err
  921. }
  922. gcp.Pricing = pages
  923. return nil
  924. }
  925. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  926. gcp.DownloadPricingDataLock.RLock()
  927. defer gcp.DownloadPricingDataLock.RUnlock()
  928. pricing, ok := gcp.Pricing[pvk.Features()]
  929. if !ok {
  930. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  931. return &PV{}, nil
  932. }
  933. return pricing.PV, nil
  934. }
  935. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  936. func (gcp *GCP) NetworkPricing() (*Network, error) {
  937. cpricing, err := gcp.Config.GetCustomPricingData()
  938. if err != nil {
  939. return nil, err
  940. }
  941. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  942. if err != nil {
  943. return nil, err
  944. }
  945. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  946. if err != nil {
  947. return nil, err
  948. }
  949. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  950. if err != nil {
  951. return nil, err
  952. }
  953. return &Network{
  954. ZoneNetworkEgressCost: znec,
  955. RegionNetworkEgressCost: rnec,
  956. InternetNetworkEgressCost: inec,
  957. }, nil
  958. }
  959. func (gcp *GCP) LoadBalancerPricing() (*LoadBalancer, error) {
  960. fffrc := 0.025
  961. afrc := 0.010
  962. lbidc := 0.008
  963. numForwardingRules := 1.0
  964. dataIngressGB := 0.0
  965. var totalCost float64
  966. if numForwardingRules < 5 {
  967. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  968. } else {
  969. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  970. }
  971. return &LoadBalancer{
  972. Cost: totalCost,
  973. }, nil
  974. }
  975. const (
  976. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  977. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  978. GCPReservedInstanceStatusActive string = "ACTIVE"
  979. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  980. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  981. )
  982. type GCPReservedInstancePlan struct {
  983. Name string
  984. CPUCost float64
  985. RAMCost float64
  986. }
  987. type GCPReservedInstance struct {
  988. ReservedRAM int64
  989. ReservedCPU int64
  990. Plan *GCPReservedInstancePlan
  991. StartDate time.Time
  992. EndDate time.Time
  993. Region string
  994. }
  995. func (r *GCPReservedInstance) String() string {
  996. 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())
  997. }
  998. type GCPReservedCounter struct {
  999. RemainingCPU int64
  1000. RemainingRAM int64
  1001. Instance *GCPReservedInstance
  1002. }
  1003. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  1004. return &GCPReservedCounter{
  1005. RemainingCPU: instance.ReservedCPU,
  1006. RemainingRAM: instance.ReservedRAM,
  1007. Instance: instance,
  1008. }
  1009. }
  1010. // Two available Reservation plans for GCP, 1-year and 3-year
  1011. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  1012. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  1013. Name: GCPReservedInstancePlanOneYear,
  1014. CPUCost: 0.019915,
  1015. RAMCost: 0.002669,
  1016. },
  1017. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  1018. Name: GCPReservedInstancePlanThreeYear,
  1019. CPUCost: 0.014225,
  1020. RAMCost: 0.001907,
  1021. },
  1022. }
  1023. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1024. numReserved := len(gcp.ReservedInstances)
  1025. // Early return if no reserved instance data loaded
  1026. if numReserved == 0 {
  1027. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1028. return
  1029. }
  1030. now := time.Now()
  1031. counters := make(map[string][]*GCPReservedCounter)
  1032. for _, r := range gcp.ReservedInstances {
  1033. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1034. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1035. continue
  1036. }
  1037. _, ok := counters[r.Region]
  1038. counter := newReservedCounter(r)
  1039. if !ok {
  1040. counters[r.Region] = []*GCPReservedCounter{counter}
  1041. } else {
  1042. counters[r.Region] = append(counters[r.Region], counter)
  1043. }
  1044. }
  1045. gcpNodes := make(map[string]*v1.Node)
  1046. currentNodes := gcp.Clientset.GetAllNodes()
  1047. // Create a node name -> node map
  1048. for _, gcpNode := range currentNodes {
  1049. gcpNodes[gcpNode.GetName()] = gcpNode
  1050. }
  1051. // go through all provider nodes using k8s nodes for region
  1052. for nodeName, node := range nodes {
  1053. // Reset reserved allocation to prevent double allocation
  1054. node.Reserved = nil
  1055. kNode, ok := gcpNodes[nodeName]
  1056. if !ok {
  1057. klog.V(4).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1058. continue
  1059. }
  1060. nodeRegion, ok := util.GetRegion(kNode.Labels)
  1061. if !ok {
  1062. klog.V(4).Infof("[Reserved] Could not find node region")
  1063. continue
  1064. }
  1065. reservedCounters, ok := counters[nodeRegion]
  1066. if !ok {
  1067. klog.V(4).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1068. continue
  1069. }
  1070. node.Reserved = &ReservedInstanceData{
  1071. ReservedCPU: 0,
  1072. ReservedRAM: 0,
  1073. }
  1074. for _, reservedCounter := range reservedCounters {
  1075. if reservedCounter.RemainingCPU != 0 {
  1076. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1077. nodeCPU -= node.Reserved.ReservedCPU
  1078. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1079. if reservedCounter.RemainingCPU >= nodeCPU {
  1080. reservedCounter.RemainingCPU -= nodeCPU
  1081. node.Reserved.ReservedCPU += nodeCPU
  1082. } else {
  1083. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1084. reservedCounter.RemainingCPU = 0
  1085. }
  1086. }
  1087. if reservedCounter.RemainingRAM != 0 {
  1088. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1089. nodeRAM := int64(nodeRAMF)
  1090. nodeRAM -= node.Reserved.ReservedRAM
  1091. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1092. if reservedCounter.RemainingRAM >= nodeRAM {
  1093. reservedCounter.RemainingRAM -= nodeRAM
  1094. node.Reserved.ReservedRAM += nodeRAM
  1095. } else {
  1096. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1097. reservedCounter.RemainingRAM = 0
  1098. }
  1099. }
  1100. }
  1101. }
  1102. }
  1103. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1104. var results []*GCPReservedInstance
  1105. ctx := context.Background()
  1106. computeService, err := compute.NewService(ctx)
  1107. if err != nil {
  1108. return nil, err
  1109. }
  1110. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1111. if err != nil {
  1112. return nil, err
  1113. }
  1114. for regionKey, commitList := range commitments.Items {
  1115. for _, commit := range commitList.Commitments {
  1116. if commit.Status != GCPReservedInstanceStatusActive {
  1117. continue
  1118. }
  1119. var vcpu int64 = 0
  1120. var ram int64 = 0
  1121. for _, resource := range commit.Resources {
  1122. switch resource.Type {
  1123. case GCPReservedInstanceResourceTypeRAM:
  1124. ram = resource.Amount * 1024 * 1024
  1125. case GCPReservedInstanceResourceTypeCPU:
  1126. vcpu = resource.Amount
  1127. default:
  1128. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  1129. }
  1130. }
  1131. var region string
  1132. regionStr := strings.Split(regionKey, "/")
  1133. if len(regionStr) == 2 {
  1134. region = regionStr[1]
  1135. }
  1136. timeLayout := "2006-01-02T15:04:05Z07:00"
  1137. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1138. if err != nil {
  1139. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  1140. continue
  1141. }
  1142. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1143. if err != nil {
  1144. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  1145. continue
  1146. }
  1147. // Look for a plan based on the name. Default to One Year if it fails
  1148. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1149. if !ok {
  1150. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1151. }
  1152. results = append(results, &GCPReservedInstance{
  1153. Region: region,
  1154. ReservedRAM: ram,
  1155. ReservedCPU: vcpu,
  1156. Plan: plan,
  1157. StartDate: startTime,
  1158. EndDate: endTime,
  1159. })
  1160. }
  1161. }
  1162. return results, nil
  1163. }
  1164. type pvKey struct {
  1165. Labels map[string]string
  1166. StorageClass string
  1167. StorageClassParameters map[string]string
  1168. DefaultRegion string
  1169. }
  1170. func (key *pvKey) ID() string {
  1171. return ""
  1172. }
  1173. func (key *pvKey) GetStorageClass() string {
  1174. return key.StorageClass
  1175. }
  1176. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  1177. return &pvKey{
  1178. Labels: pv.Labels,
  1179. StorageClass: pv.Spec.StorageClassName,
  1180. StorageClassParameters: parameters,
  1181. DefaultRegion: defaultRegion,
  1182. }
  1183. }
  1184. func (key *pvKey) Features() string {
  1185. // TODO: regional cluster pricing.
  1186. storageClass := key.StorageClassParameters["type"]
  1187. if storageClass == "pd-ssd" {
  1188. storageClass = "ssd"
  1189. } else if storageClass == "pd-standard" {
  1190. storageClass = "pdstandard"
  1191. }
  1192. region, _ := util.GetRegion(key.Labels)
  1193. return region + "," + storageClass
  1194. }
  1195. type gcpKey struct {
  1196. Labels map[string]string
  1197. }
  1198. func (gcp *GCP) GetKey(labels map[string]string, n *v1.Node) Key {
  1199. return &gcpKey{
  1200. Labels: labels,
  1201. }
  1202. }
  1203. func (gcp *gcpKey) ID() string {
  1204. return ""
  1205. }
  1206. func (gcp *gcpKey) GPUType() string {
  1207. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1208. var usageType string
  1209. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1210. usageType = "preemptible"
  1211. } else {
  1212. usageType = "ondemand"
  1213. }
  1214. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  1215. return t + "," + usageType
  1216. }
  1217. return ""
  1218. }
  1219. // GetKey maps node labels to information needed to retrieve pricing data
  1220. func (gcp *gcpKey) Features() string {
  1221. it, _ := util.GetInstanceType(gcp.Labels)
  1222. instanceType := strings.ToLower(strings.Join(strings.Split(it, "-")[:2], ""))
  1223. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1224. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1225. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1226. instanceType = "n2standard"
  1227. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1228. instanceType = "e2standard"
  1229. } else if strings.HasPrefix(instanceType, "custom") {
  1230. instanceType = "custom" // The suffix of custom does not matter
  1231. }
  1232. r, _ := util.GetRegion(gcp.Labels)
  1233. region := strings.ToLower(r)
  1234. var usageType string
  1235. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1236. usageType = "preemptible"
  1237. } else {
  1238. usageType = "ondemand"
  1239. }
  1240. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1241. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1242. }
  1243. return region + "," + instanceType + "," + usageType
  1244. }
  1245. // AllNodePricing returns the GCP pricing objects stored
  1246. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1247. gcp.DownloadPricingDataLock.RLock()
  1248. defer gcp.DownloadPricingDataLock.RUnlock()
  1249. return gcp.Pricing, nil
  1250. }
  1251. func (gcp *GCP) getPricing(key Key) (*GCPPricing, bool) {
  1252. gcp.DownloadPricingDataLock.RLock()
  1253. defer gcp.DownloadPricingDataLock.RUnlock()
  1254. n, ok := gcp.Pricing[key.Features()]
  1255. return n, ok
  1256. }
  1257. func (gcp *GCP) isValidPricingKey(key Key) bool {
  1258. gcp.DownloadPricingDataLock.RLock()
  1259. defer gcp.DownloadPricingDataLock.RUnlock()
  1260. _, ok := gcp.ValidPricingKeys[key.Features()]
  1261. return ok
  1262. }
  1263. // NodePricing returns GCP pricing data for a single node
  1264. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  1265. if n, ok := gcp.getPricing(key); ok {
  1266. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1267. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1268. return n.Node, nil
  1269. } else if ok := gcp.isValidPricingKey(key); ok {
  1270. err := gcp.DownloadPricingData()
  1271. if err != nil {
  1272. return nil, fmt.Errorf("Download pricing data failed: %s", err.Error())
  1273. }
  1274. if n, ok := gcp.getPricing(key); ok {
  1275. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1276. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1277. return n.Node, nil
  1278. }
  1279. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  1280. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1281. }
  1282. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1283. }
  1284. func (gcp *GCP) ServiceAccountStatus() *ServiceAccountStatus {
  1285. return &ServiceAccountStatus{
  1286. Checks: []*ServiceAccountCheck{},
  1287. }
  1288. }
  1289. func (gcp *GCP) PricingSourceStatus() map[string]*PricingSource {
  1290. return make(map[string]*PricingSource)
  1291. }
  1292. func (gcp *GCP) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1293. class := strings.Split(instanceType, "-")[0]
  1294. return 1.0 - ((1.0 - sustainedUseDiscount(class, defaultDiscount, isPreemptible)) * (1.0 - negotiatedDiscount))
  1295. }
  1296. func sustainedUseDiscount(class string, defaultDiscount float64, isPreemptible bool) float64 {
  1297. if isPreemptible {
  1298. return 0.0
  1299. }
  1300. discount := defaultDiscount
  1301. switch class {
  1302. case "e2", "f1", "g1":
  1303. discount = 0.0
  1304. case "n2", "n2d":
  1305. discount = 0.2
  1306. }
  1307. return discount
  1308. }
  1309. func (gcp *GCP) ParseID(id string) string {
  1310. // gce://guestbook-227502/us-central1-a/gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  1311. // => gke-niko-n1-standard-2-wljla-8df8e58a-hfy7
  1312. rx := regexp.MustCompile("gce://[^/]*/[^/]*/([^/]+)")
  1313. match := rx.FindStringSubmatch(id)
  1314. if len(match) < 2 {
  1315. if id != "" {
  1316. log.Infof("gcpprovider.ParseID: failed to parse %s", id)
  1317. }
  1318. return id
  1319. }
  1320. return match[1]
  1321. }
  1322. func (gcp *GCP) ParsePVID(id string) string {
  1323. return id
  1324. }