gcpprovider.go 48 KB

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