gcpprovider.go 24 KB

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