gcpprovider.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "k8s.io/klog"
  17. "cloud.google.com/go/bigquery"
  18. "cloud.google.com/go/compute/metadata"
  19. "golang.org/x/oauth2"
  20. "golang.org/x/oauth2/google"
  21. compute "google.golang.org/api/compute/v1"
  22. "google.golang.org/api/iterator"
  23. v1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/client-go/kubernetes"
  26. )
  27. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  28. const BigqueryUpdateType = "bigqueryupdate"
  29. type userAgentTransport struct {
  30. userAgent string
  31. base http.RoundTripper
  32. }
  33. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  34. req.Header.Set("User-Agent", t.userAgent)
  35. return t.base.RoundTrip(req)
  36. }
  37. // GCP implements a provider interface for GCP
  38. type GCP struct {
  39. Pricing map[string]*GCPPricing
  40. Clientset *kubernetes.Clientset
  41. APIKey string
  42. BaseCPUPrice string
  43. ProjectID string
  44. BillingDataDataset string
  45. DownloadPricingDataLock sync.RWMutex
  46. *CustomProvider
  47. }
  48. type gcpAllocation struct {
  49. Aggregator bigquery.NullString
  50. Environment bigquery.NullString
  51. Service string
  52. Cost float64
  53. }
  54. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  55. var aggregator string
  56. if gcpAlloc.Aggregator.Valid {
  57. aggregator = gcpAlloc.Aggregator.StringVal
  58. }
  59. var environment string
  60. if gcpAlloc.Environment.Valid {
  61. environment = gcpAlloc.Environment.StringVal
  62. }
  63. return &OutOfClusterAllocation{
  64. Aggregator: aggregator,
  65. Environment: environment,
  66. Service: gcpAlloc.Service,
  67. Cost: gcpAlloc.Cost,
  68. }
  69. }
  70. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  71. c, err := GetDefaultPricingData("gcp.json")
  72. if err != nil {
  73. return nil, err
  74. }
  75. return c, nil
  76. }
  77. type BigQueryConfig struct {
  78. ProjectID string `json:"projectID"`
  79. BillingDataDataset string `json:"billingDataDataset"`
  80. Key map[string]string `json:"key"`
  81. }
  82. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  83. c, err := GetDefaultPricingData("gcp.json")
  84. if err != nil {
  85. return nil, err
  86. }
  87. path := os.Getenv("CONFIG_PATH")
  88. if path == "" {
  89. path = "/models/"
  90. }
  91. if updateType == BigqueryUpdateType {
  92. a := BigQueryConfig{}
  93. err = json.NewDecoder(r).Decode(&a)
  94. if err != nil {
  95. return nil, err
  96. }
  97. c.ProjectID = a.ProjectID
  98. c.BillingDataDataset = a.BillingDataDataset
  99. j, err := json.Marshal(a.Key)
  100. if err != nil {
  101. return nil, err
  102. }
  103. keyPath := path + "key.json"
  104. err = ioutil.WriteFile(keyPath, j, 0644)
  105. if err != nil {
  106. return nil, err
  107. }
  108. } else {
  109. a := make(map[string]string)
  110. err = json.NewDecoder(r).Decode(&a)
  111. if err != nil {
  112. return nil, err
  113. }
  114. for k, v := range a {
  115. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  116. err := SetCustomPricingField(c, kUpper, v)
  117. if err != nil {
  118. return nil, err
  119. }
  120. }
  121. }
  122. cj, err := json.Marshal(c)
  123. if err != nil {
  124. return nil, err
  125. }
  126. configPath := path + "gcp.json"
  127. err = ioutil.WriteFile(configPath, cj, 0644)
  128. if err != nil {
  129. return nil, err
  130. }
  131. return c, nil
  132. }
  133. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  134. // "start" and "end" are dates of the format YYYY-MM-DD
  135. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  136. func (gcp *GCP) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  137. c, err := GetDefaultPricingData("gcp.json")
  138. if err != nil {
  139. return nil, err
  140. }
  141. // start, end formatted like: "2019-04-20 00:00:00"
  142. queryString := fmt.Sprintf(`SELECT
  143. service,
  144. labels.key as aggregator,
  145. labels.value as environment,
  146. SUM(cost) as cost
  147. FROM (SELECT
  148. service.description as service,
  149. labels,
  150. cost
  151. FROM %s
  152. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  153. LEFT JOIN UNNEST(labels) as labels
  154. ON labels.key = "kubernetes_namespace" OR labels.key = "kubernetes_container" OR labels.key = "kubernetes_deployment" OR labels.key = "kubernetes_pod" OR labels.key = "kubernetes_daemonset"
  155. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  156. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  157. return gcp.QuerySQL(queryString)
  158. }
  159. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  160. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  161. c, err := GetDefaultPricingData("gcp.json")
  162. if err != nil {
  163. return nil, err
  164. }
  165. ctx := context.Background()
  166. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  167. if err != nil {
  168. return nil, err
  169. }
  170. q := client.Query(query)
  171. it, err := q.Read(ctx)
  172. if err != nil {
  173. return nil, err
  174. }
  175. var allocations []*OutOfClusterAllocation
  176. for {
  177. var a gcpAllocation
  178. err := it.Next(&a)
  179. if err == iterator.Done {
  180. break
  181. }
  182. if err != nil {
  183. return nil, err
  184. }
  185. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  186. }
  187. return allocations, nil
  188. }
  189. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  190. func (*GCP) ClusterName() ([]byte, error) {
  191. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  192. userAgent: "kubecost",
  193. base: http.DefaultTransport,
  194. }})
  195. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  196. if err != nil {
  197. return nil, err
  198. }
  199. m := make(map[string]string)
  200. m["name"] = attribute
  201. m["provider"] = "GCP"
  202. return json.Marshal(m)
  203. }
  204. // AddServiceKey adds the service key as required for GetDisks
  205. func (*GCP) AddServiceKey(formValues url.Values) error {
  206. key := formValues.Get("key")
  207. k := []byte(key)
  208. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  209. }
  210. // 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.
  211. func (*GCP) GetDisks() ([]byte, error) {
  212. // metadata API setup
  213. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  214. userAgent: "kubecost",
  215. base: http.DefaultTransport,
  216. }})
  217. projID, err := metadataClient.ProjectID()
  218. if err != nil {
  219. return nil, err
  220. }
  221. client, err := google.DefaultClient(oauth2.NoContext,
  222. "https://www.googleapis.com/auth/compute.readonly")
  223. if err != nil {
  224. return nil, err
  225. }
  226. svc, err := compute.New(client)
  227. if err != nil {
  228. return nil, err
  229. }
  230. res, err := svc.Disks.AggregatedList(projID).Do()
  231. if err != nil {
  232. return nil, err
  233. }
  234. return json.Marshal(res)
  235. }
  236. // GCPPricing represents GCP pricing data for a SKU
  237. type GCPPricing struct {
  238. Name string `json:"name"`
  239. SKUID string `json:"skuId"`
  240. Description string `json:"description"`
  241. Category *GCPResourceInfo `json:"category"`
  242. ServiceRegions []string `json:"serviceRegions"`
  243. PricingInfo []*PricingInfo `json:"pricingInfo"`
  244. ServiceProviderName string `json:"serviceProviderName"`
  245. Node *Node `json:"node"`
  246. PV *PV `json:"pv"`
  247. }
  248. // PricingInfo contains metadata about a cost.
  249. type PricingInfo struct {
  250. Summary string `json:"summary"`
  251. PricingExpression *PricingExpression `json:"pricingExpression"`
  252. CurrencyConversionRate int `json:"currencyConversionRate"`
  253. EffectiveTime string `json:""`
  254. }
  255. // PricingExpression contains metadata about a cost.
  256. type PricingExpression struct {
  257. UsageUnit string `json:"usageUnit"`
  258. UsageUnitDescription string `json:"usageUnitDescription"`
  259. BaseUnit string `json:"baseUnit"`
  260. BaseUnitConversionFactor int64 `json:"-"`
  261. DisplayQuantity int `json:"displayQuantity"`
  262. TieredRates []*TieredRates `json:"tieredRates"`
  263. }
  264. // TieredRates contain data about variable pricing.
  265. type TieredRates struct {
  266. StartUsageAmount int `json:"startUsageAmount"`
  267. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  268. }
  269. // UnitPriceInfo contains data about the actual price being charged.
  270. type UnitPriceInfo struct {
  271. CurrencyCode string `json:"currencyCode"`
  272. Units string `json:"units"`
  273. Nanos float64 `json:"nanos"`
  274. }
  275. // GCPResourceInfo contains metadata about the node.
  276. type GCPResourceInfo struct {
  277. ServiceDisplayName string `json:"serviceDisplayName"`
  278. ResourceFamily string `json:"resourceFamily"`
  279. ResourceGroup string `json:"resourceGroup"`
  280. UsageType string `json:"usageType"`
  281. }
  282. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  283. gcpPricingList := make(map[string]*GCPPricing)
  284. var nextPageToken string
  285. dec := json.NewDecoder(r)
  286. for {
  287. t, err := dec.Token()
  288. if err == io.EOF {
  289. break
  290. }
  291. if t == "skus" {
  292. _, err := dec.Token() // consumes [
  293. if err != nil {
  294. return nil, "", err
  295. }
  296. for dec.More() {
  297. product := &GCPPricing{}
  298. err := dec.Decode(&product)
  299. if err != nil {
  300. return nil, "", err
  301. }
  302. usageType := strings.ToLower(product.Category.UsageType)
  303. instanceType := strings.ToLower(product.Category.ResourceGroup)
  304. if instanceType == "ssd" {
  305. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  306. var nanos float64
  307. if len(product.PricingInfo) > 0 {
  308. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  309. } else {
  310. continue
  311. }
  312. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  313. for _, sr := range product.ServiceRegions {
  314. region := sr
  315. candidateKey := region + "," + "ssd"
  316. if _, ok := pvKeys[candidateKey]; ok {
  317. product.PV = &PV{
  318. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  319. }
  320. gcpPricingList[candidateKey] = product
  321. continue
  322. }
  323. }
  324. continue
  325. } else if instanceType == "pdstandard" {
  326. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  327. var nanos float64
  328. if len(product.PricingInfo) > 0 {
  329. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  330. } else {
  331. continue
  332. }
  333. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  334. for _, sr := range product.ServiceRegions {
  335. region := sr
  336. candidateKey := region + "," + "pdstandard"
  337. if _, ok := pvKeys[candidateKey]; ok {
  338. product.PV = &PV{
  339. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  340. }
  341. gcpPricingList[candidateKey] = product
  342. continue
  343. }
  344. }
  345. continue
  346. }
  347. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  348. instanceType = "custom"
  349. }
  350. var partialCPU float64
  351. if strings.ToLower(instanceType) == "f1micro" {
  352. partialCPU = 0.2
  353. } else if strings.ToLower(instanceType) == "g1small" {
  354. partialCPU = 0.5
  355. }
  356. var gpuType string
  357. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  358. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  359. if matchnum == 1 {
  360. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  361. klog.V(4).Info("GPU type found: " + gpuType)
  362. }
  363. }
  364. for _, sr := range product.ServiceRegions {
  365. region := sr
  366. candidateKey := region + "," + instanceType + "," + usageType
  367. candidateKeyGPU := candidateKey + ",gpu"
  368. if gpuType != "" {
  369. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  370. var nanos float64
  371. if len(product.PricingInfo) > 0 {
  372. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  373. } else {
  374. continue
  375. }
  376. hourlyPrice := nanos * math.Pow10(-9)
  377. for k, key := range inputKeys {
  378. if key.GPUType() == gpuType+","+usageType {
  379. if region == strings.Split(k, ",")[0] {
  380. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  381. matchedKey := key.Features()
  382. if pl, ok := gcpPricingList[matchedKey]; ok {
  383. pl.Node.GPUName = gpuType
  384. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  385. pl.Node.GPU = "1"
  386. } else {
  387. product.Node = &Node{
  388. GPUName: gpuType,
  389. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  390. GPU: "1",
  391. }
  392. gcpPricingList[matchedKey] = product
  393. }
  394. klog.V(3).Infof("Added data for " + matchedKey)
  395. }
  396. }
  397. }
  398. } else {
  399. _, ok := inputKeys[candidateKey]
  400. _, ok2 := inputKeys[candidateKeyGPU]
  401. if ok || ok2 {
  402. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  403. var nanos float64
  404. if len(product.PricingInfo) > 0 {
  405. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  406. } else {
  407. continue
  408. }
  409. hourlyPrice := nanos * math.Pow10(-9)
  410. if hourlyPrice == 0 {
  411. continue
  412. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  413. if instanceType == "custom" {
  414. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  415. }
  416. if _, ok := gcpPricingList[candidateKey]; ok {
  417. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  418. } else {
  419. product = &GCPPricing{}
  420. product.Node = &Node{
  421. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  422. }
  423. if partialCPU != 0 {
  424. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  425. }
  426. product.Node.UsageType = usageType
  427. gcpPricingList[candidateKey] = product
  428. }
  429. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  430. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  431. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  432. } else {
  433. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  434. product = &GCPPricing{}
  435. product.Node = &Node{
  436. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  437. }
  438. if partialCPU != 0 {
  439. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  440. }
  441. product.Node.UsageType = usageType
  442. gcpPricingList[candidateKeyGPU] = product
  443. }
  444. break
  445. } else {
  446. if _, ok := gcpPricingList[candidateKey]; ok {
  447. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  448. } else {
  449. product = &GCPPricing{}
  450. product.Node = &Node{
  451. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  452. }
  453. if partialCPU != 0 {
  454. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  455. }
  456. product.Node.UsageType = usageType
  457. gcpPricingList[candidateKey] = product
  458. }
  459. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  460. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  461. } else {
  462. product = &GCPPricing{}
  463. product.Node = &Node{
  464. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  465. }
  466. if partialCPU != 0 {
  467. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  468. }
  469. product.Node.UsageType = usageType
  470. gcpPricingList[candidateKeyGPU] = product
  471. }
  472. break
  473. }
  474. }
  475. }
  476. }
  477. }
  478. }
  479. if t == "nextPageToken" {
  480. pageToken, err := dec.Token()
  481. if err != nil {
  482. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  483. return nil, "", err
  484. }
  485. if pageToken.(string) != "" {
  486. nextPageToken = pageToken.(string)
  487. } else {
  488. nextPageToken = "done"
  489. }
  490. }
  491. }
  492. return gcpPricingList, nextPageToken, nil
  493. }
  494. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  495. var pages []map[string]*GCPPricing
  496. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  497. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  498. var parsePagesHelper func(string) error
  499. parsePagesHelper = func(pageToken string) error {
  500. if pageToken == "done" {
  501. return nil
  502. } else if pageToken != "" {
  503. url = url + "&pageToken=" + pageToken
  504. }
  505. resp, err := http.Get(url)
  506. if err != nil {
  507. return err
  508. }
  509. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  510. if err != nil {
  511. return err
  512. }
  513. pages = append(pages, page)
  514. return parsePagesHelper(token)
  515. }
  516. err := parsePagesHelper("")
  517. if err != nil {
  518. return nil, err
  519. }
  520. returnPages := make(map[string]*GCPPricing)
  521. for _, page := range pages {
  522. klog.V(1).Infof("Page: %s : %+v", page)
  523. for k, v := range page {
  524. klog.V(1).Infof("Unmerged Page: %s : %+v", k, v)
  525. }
  526. }
  527. for _, page := range pages {
  528. for k, v := range page {
  529. if val, ok := returnPages[k]; ok { //keys may need to be merged
  530. if val.Node != nil {
  531. if val.Node.VCPUCost == "" {
  532. val.Node.VCPUCost = v.Node.VCPUCost
  533. }
  534. if val.Node.RAMCost == "" {
  535. val.Node.RAMCost = v.Node.RAMCost
  536. }
  537. if val.Node.GPUCost == "" {
  538. val.Node.GPUCost = v.Node.GPUCost
  539. }
  540. }
  541. if val.PV != nil {
  542. if val.PV.Cost == "" {
  543. val.PV.Cost = v.PV.Cost
  544. }
  545. }
  546. } else {
  547. returnPages[k] = v
  548. }
  549. }
  550. }
  551. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  552. for k, v := range returnPages {
  553. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  554. }
  555. return returnPages, err
  556. }
  557. // 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.
  558. func (gcp *GCP) DownloadPricingData() error {
  559. gcp.DownloadPricingDataLock.Lock()
  560. defer gcp.DownloadPricingDataLock.Unlock()
  561. c, err := GetDefaultPricingData("gcp.json")
  562. if err != nil {
  563. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  564. return err
  565. }
  566. gcp.BaseCPUPrice = c.CPU
  567. gcp.ProjectID = c.ProjectID
  568. gcp.BillingDataDataset = c.BillingDataDataset
  569. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  570. if err != nil {
  571. return err
  572. }
  573. inputkeys := make(map[string]Key)
  574. for _, n := range nodeList.Items {
  575. labels := n.GetObjectMeta().GetLabels()
  576. key := gcp.GetKey(labels)
  577. inputkeys[key.Features()] = key
  578. }
  579. pvList, err := gcp.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  580. if err != nil {
  581. return err
  582. }
  583. storageClasses, err := gcp.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  584. storageClassMap := make(map[string]map[string]string)
  585. for _, storageClass := range storageClasses.Items {
  586. params := storageClass.Parameters
  587. storageClassMap[storageClass.ObjectMeta.Name] = params
  588. }
  589. pvkeys := make(map[string]PVKey)
  590. for _, pv := range pvList.Items {
  591. params, ok := storageClassMap[pv.Spec.StorageClassName]
  592. if !ok {
  593. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  594. continue
  595. }
  596. key := gcp.GetPVKey(&pv, params)
  597. pvkeys[key.Features()] = key
  598. }
  599. pages, err := gcp.parsePages(inputkeys, pvkeys)
  600. if err != nil {
  601. return err
  602. }
  603. gcp.Pricing = pages
  604. return nil
  605. }
  606. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  607. gcp.DownloadPricingDataLock.RLock()
  608. defer gcp.DownloadPricingDataLock.RUnlock()
  609. pricing, ok := gcp.Pricing[pvk.Features()]
  610. if !ok {
  611. klog.V(2).Infof("Persistent Volume pricing not found for %s", pvk)
  612. return &PV{}, nil
  613. }
  614. return pricing.PV, nil
  615. }
  616. type pvKey struct {
  617. Labels map[string]string
  618. StorageClass string
  619. StorageClassParameters map[string]string
  620. }
  621. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  622. return &pvKey{
  623. Labels: pv.Labels,
  624. StorageClass: pv.Spec.StorageClassName,
  625. StorageClassParameters: parameters,
  626. }
  627. }
  628. func (key *pvKey) Features() string {
  629. storageClass := key.StorageClassParameters["type"]
  630. if storageClass == "pd-ssd" {
  631. storageClass = "ssd"
  632. } else if storageClass == "pd-standard" {
  633. storageClass = "pdstandard"
  634. }
  635. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  636. }
  637. type gcpKey struct {
  638. Labels map[string]string
  639. }
  640. func (gcp *GCP) GetKey(labels map[string]string) Key {
  641. return &gcpKey{
  642. Labels: labels,
  643. }
  644. }
  645. func (gcp *gcpKey) ID() string {
  646. return ""
  647. }
  648. func (gcp *gcpKey) GPUType() string {
  649. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  650. var usageType string
  651. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  652. usageType = "preemptible"
  653. } else {
  654. usageType = "ondemand"
  655. }
  656. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  657. return t + "," + usageType
  658. }
  659. return ""
  660. }
  661. // GetKey maps node labels to information needed to retrieve pricing data
  662. func (gcp *gcpKey) Features() string {
  663. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  664. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  665. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  666. } else if strings.HasPrefix(instanceType, "custom") {
  667. instanceType = "custom" // The suffix of custom does not matter
  668. }
  669. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  670. var usageType string
  671. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  672. usageType = "preemptible"
  673. } else {
  674. usageType = "ondemand"
  675. }
  676. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  677. return region + "," + instanceType + "," + usageType + "," + "gpu"
  678. }
  679. return region + "," + instanceType + "," + usageType
  680. }
  681. // AllNodePricing returns the GCP pricing objects stored
  682. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  683. gcp.DownloadPricingDataLock.RLock()
  684. defer gcp.DownloadPricingDataLock.RUnlock()
  685. return gcp.Pricing, nil
  686. }
  687. // NodePricing returns GCP pricing data for a single node
  688. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  689. gcp.DownloadPricingDataLock.RLock()
  690. defer gcp.DownloadPricingDataLock.RUnlock()
  691. if n, ok := gcp.Pricing[key.Features()]; ok {
  692. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  693. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  694. return n.Node, nil
  695. }
  696. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  697. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  698. }