gcpprovider.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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(3).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) 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. m := make(map[string]string)
  221. m["name"] = attribute
  222. m["provider"] = "GCP"
  223. return m, nil
  224. }
  225. // AddServiceKey adds the service key as required for GetDisks
  226. func (*GCP) AddServiceKey(formValues url.Values) error {
  227. key := formValues.Get("key")
  228. k := []byte(key)
  229. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  230. }
  231. // 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.
  232. func (*GCP) GetDisks() ([]byte, error) {
  233. // metadata API setup
  234. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  235. userAgent: "kubecost",
  236. base: http.DefaultTransport,
  237. }})
  238. projID, err := metadataClient.ProjectID()
  239. if err != nil {
  240. return nil, err
  241. }
  242. client, err := google.DefaultClient(oauth2.NoContext,
  243. "https://www.googleapis.com/auth/compute.readonly")
  244. if err != nil {
  245. return nil, err
  246. }
  247. svc, err := compute.New(client)
  248. if err != nil {
  249. return nil, err
  250. }
  251. res, err := svc.Disks.AggregatedList(projID).Do()
  252. if err != nil {
  253. return nil, err
  254. }
  255. return json.Marshal(res)
  256. }
  257. // GCPPricing represents GCP pricing data for a SKU
  258. type GCPPricing struct {
  259. Name string `json:"name"`
  260. SKUID string `json:"skuId"`
  261. Description string `json:"description"`
  262. Category *GCPResourceInfo `json:"category"`
  263. ServiceRegions []string `json:"serviceRegions"`
  264. PricingInfo []*PricingInfo `json:"pricingInfo"`
  265. ServiceProviderName string `json:"serviceProviderName"`
  266. Node *Node `json:"node"`
  267. PV *PV `json:"pv"`
  268. }
  269. // PricingInfo contains metadata about a cost.
  270. type PricingInfo struct {
  271. Summary string `json:"summary"`
  272. PricingExpression *PricingExpression `json:"pricingExpression"`
  273. CurrencyConversionRate int `json:"currencyConversionRate"`
  274. EffectiveTime string `json:""`
  275. }
  276. // PricingExpression contains metadata about a cost.
  277. type PricingExpression struct {
  278. UsageUnit string `json:"usageUnit"`
  279. UsageUnitDescription string `json:"usageUnitDescription"`
  280. BaseUnit string `json:"baseUnit"`
  281. BaseUnitConversionFactor int64 `json:"-"`
  282. DisplayQuantity int `json:"displayQuantity"`
  283. TieredRates []*TieredRates `json:"tieredRates"`
  284. }
  285. // TieredRates contain data about variable pricing.
  286. type TieredRates struct {
  287. StartUsageAmount int `json:"startUsageAmount"`
  288. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  289. }
  290. // UnitPriceInfo contains data about the actual price being charged.
  291. type UnitPriceInfo struct {
  292. CurrencyCode string `json:"currencyCode"`
  293. Units string `json:"units"`
  294. Nanos float64 `json:"nanos"`
  295. }
  296. // GCPResourceInfo contains metadata about the node.
  297. type GCPResourceInfo struct {
  298. ServiceDisplayName string `json:"serviceDisplayName"`
  299. ResourceFamily string `json:"resourceFamily"`
  300. ResourceGroup string `json:"resourceGroup"`
  301. UsageType string `json:"usageType"`
  302. }
  303. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  304. gcpPricingList := make(map[string]*GCPPricing)
  305. var nextPageToken string
  306. dec := json.NewDecoder(r)
  307. for {
  308. t, err := dec.Token()
  309. if err == io.EOF {
  310. break
  311. }
  312. if t == "skus" {
  313. _, err := dec.Token() // consumes [
  314. if err != nil {
  315. return nil, "", err
  316. }
  317. for dec.More() {
  318. product := &GCPPricing{}
  319. err := dec.Decode(&product)
  320. if err != nil {
  321. return nil, "", err
  322. }
  323. usageType := strings.ToLower(product.Category.UsageType)
  324. instanceType := strings.ToLower(product.Category.ResourceGroup)
  325. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  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 + "," + "ssd"
  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. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  347. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  348. var nanos float64
  349. if len(product.PricingInfo) > 0 {
  350. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  351. } else {
  352. continue
  353. }
  354. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  355. for _, sr := range product.ServiceRegions {
  356. region := sr
  357. candidateKey := region + "," + "pdstandard"
  358. if _, ok := pvKeys[candidateKey]; ok {
  359. product.PV = &PV{
  360. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  361. }
  362. gcpPricingList[candidateKey] = product
  363. continue
  364. }
  365. }
  366. continue
  367. }
  368. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  369. instanceType = "custom"
  370. }
  371. /*
  372. var partialCPU float64
  373. if strings.ToLower(instanceType) == "f1micro" {
  374. partialCPU = 0.2
  375. } else if strings.ToLower(instanceType) == "g1small" {
  376. partialCPU = 0.5
  377. }
  378. */
  379. var gpuType string
  380. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  381. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  382. if matchnum == 1 {
  383. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  384. klog.V(4).Info("GPU type found: " + gpuType)
  385. }
  386. }
  387. for _, sr := range product.ServiceRegions {
  388. region := sr
  389. candidateKey := region + "," + instanceType + "," + usageType
  390. candidateKeyGPU := candidateKey + ",gpu"
  391. if gpuType != "" {
  392. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  393. var nanos float64
  394. if len(product.PricingInfo) > 0 {
  395. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  396. } else {
  397. continue
  398. }
  399. hourlyPrice := nanos * math.Pow10(-9)
  400. for k, key := range inputKeys {
  401. if key.GPUType() == gpuType+","+usageType {
  402. if region == strings.Split(k, ",")[0] {
  403. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  404. matchedKey := key.Features()
  405. if pl, ok := gcpPricingList[matchedKey]; ok {
  406. pl.Node.GPUName = gpuType
  407. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  408. pl.Node.GPU = "1"
  409. } else {
  410. product.Node = &Node{
  411. GPUName: gpuType,
  412. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  413. GPU: "1",
  414. }
  415. gcpPricingList[matchedKey] = product
  416. }
  417. klog.V(3).Infof("Added data for " + matchedKey)
  418. }
  419. }
  420. }
  421. } else {
  422. _, ok := inputKeys[candidateKey]
  423. _, ok2 := inputKeys[candidateKeyGPU]
  424. if ok || ok2 {
  425. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  426. var nanos float64
  427. if len(product.PricingInfo) > 0 {
  428. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  429. } else {
  430. continue
  431. }
  432. hourlyPrice := nanos * math.Pow10(-9)
  433. if hourlyPrice == 0 {
  434. continue
  435. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  436. if instanceType == "custom" {
  437. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  438. }
  439. if _, ok := gcpPricingList[candidateKey]; ok {
  440. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  441. } else {
  442. product = &GCPPricing{}
  443. product.Node = &Node{
  444. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  445. }
  446. /*
  447. if partialCPU != 0 {
  448. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  449. }
  450. */
  451. product.Node.UsageType = usageType
  452. gcpPricingList[candidateKey] = product
  453. }
  454. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  455. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  456. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  457. } else {
  458. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  459. product = &GCPPricing{}
  460. product.Node = &Node{
  461. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  462. }
  463. /*
  464. if partialCPU != 0 {
  465. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  466. }
  467. */
  468. product.Node.UsageType = usageType
  469. gcpPricingList[candidateKeyGPU] = product
  470. }
  471. break
  472. } else {
  473. if _, ok := gcpPricingList[candidateKey]; ok {
  474. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  475. } else {
  476. product = &GCPPricing{}
  477. product.Node = &Node{
  478. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  479. }
  480. /*
  481. if partialCPU != 0 {
  482. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  483. }
  484. */
  485. product.Node.UsageType = usageType
  486. gcpPricingList[candidateKey] = product
  487. }
  488. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  489. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  490. } else {
  491. product = &GCPPricing{}
  492. product.Node = &Node{
  493. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  494. }
  495. /*
  496. if partialCPU != 0 {
  497. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  498. }
  499. */
  500. product.Node.UsageType = usageType
  501. gcpPricingList[candidateKeyGPU] = product
  502. }
  503. break
  504. }
  505. }
  506. }
  507. }
  508. }
  509. }
  510. if t == "nextPageToken" {
  511. pageToken, err := dec.Token()
  512. if err != nil {
  513. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  514. return nil, "", err
  515. }
  516. if pageToken.(string) != "" {
  517. nextPageToken = pageToken.(string)
  518. } else {
  519. nextPageToken = "done"
  520. }
  521. }
  522. }
  523. return gcpPricingList, nextPageToken, nil
  524. }
  525. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  526. var pages []map[string]*GCPPricing
  527. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  528. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  529. var parsePagesHelper func(string) error
  530. parsePagesHelper = func(pageToken string) error {
  531. if pageToken == "done" {
  532. return nil
  533. } else if pageToken != "" {
  534. url = url + "&pageToken=" + pageToken
  535. }
  536. resp, err := http.Get(url)
  537. if err != nil {
  538. return err
  539. }
  540. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  541. if err != nil {
  542. return err
  543. }
  544. pages = append(pages, page)
  545. return parsePagesHelper(token)
  546. }
  547. err := parsePagesHelper("")
  548. if err != nil {
  549. return nil, err
  550. }
  551. returnPages := make(map[string]*GCPPricing)
  552. for _, page := range pages {
  553. klog.V(1).Infof("Page: %s : %+v", page)
  554. for k, v := range page {
  555. klog.V(1).Infof("Unmerged Page: %s : %+v", k, v)
  556. }
  557. }
  558. for _, page := range pages {
  559. for k, v := range page {
  560. if val, ok := returnPages[k]; ok { //keys may need to be merged
  561. if val.Node != nil {
  562. if val.Node.VCPUCost == "" {
  563. val.Node.VCPUCost = v.Node.VCPUCost
  564. }
  565. if val.Node.RAMCost == "" {
  566. val.Node.RAMCost = v.Node.RAMCost
  567. }
  568. if val.Node.GPUCost == "" {
  569. val.Node.GPUCost = v.Node.GPUCost
  570. }
  571. }
  572. if val.PV != nil {
  573. if val.PV.Cost == "" {
  574. val.PV.Cost = v.PV.Cost
  575. }
  576. }
  577. } else {
  578. returnPages[k] = v
  579. }
  580. }
  581. }
  582. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  583. for k, v := range returnPages {
  584. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  585. }
  586. return returnPages, err
  587. }
  588. // 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.
  589. func (gcp *GCP) DownloadPricingData() error {
  590. gcp.DownloadPricingDataLock.Lock()
  591. defer gcp.DownloadPricingDataLock.Unlock()
  592. c, err := GetDefaultPricingData("gcp.json")
  593. if err != nil {
  594. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  595. return err
  596. }
  597. gcp.BaseCPUPrice = c.CPU
  598. gcp.ProjectID = c.ProjectID
  599. gcp.BillingDataDataset = c.BillingDataDataset
  600. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  601. if err != nil {
  602. return err
  603. }
  604. inputkeys := make(map[string]Key)
  605. for _, n := range nodeList.Items {
  606. labels := n.GetObjectMeta().GetLabels()
  607. key := gcp.GetKey(labels)
  608. inputkeys[key.Features()] = key
  609. }
  610. pvList, err := gcp.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  611. if err != nil {
  612. return err
  613. }
  614. storageClasses, err := gcp.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  615. storageClassMap := make(map[string]map[string]string)
  616. for _, storageClass := range storageClasses.Items {
  617. params := storageClass.Parameters
  618. storageClassMap[storageClass.ObjectMeta.Name] = params
  619. }
  620. pvkeys := make(map[string]PVKey)
  621. for _, pv := range pvList.Items {
  622. params, ok := storageClassMap[pv.Spec.StorageClassName]
  623. if !ok {
  624. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  625. continue
  626. }
  627. key := gcp.GetPVKey(&pv, params)
  628. pvkeys[key.Features()] = key
  629. }
  630. pages, err := gcp.parsePages(inputkeys, pvkeys)
  631. if err != nil {
  632. return err
  633. }
  634. gcp.Pricing = pages
  635. return nil
  636. }
  637. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  638. if pvk.GetStorageClass() == "" {
  639. klog.V(3).Infof("Disk in %s does not have a storageclass set, cannot look up pricing info.", pvk.Features())
  640. return &PV{}, nil
  641. }
  642. gcp.DownloadPricingDataLock.RLock()
  643. defer gcp.DownloadPricingDataLock.RUnlock()
  644. pricing, ok := gcp.Pricing[pvk.Features()]
  645. if !ok {
  646. klog.V(2).Infof("Persistent Volume pricing not found for %s", pvk)
  647. return &PV{}, nil
  648. }
  649. return pricing.PV, nil
  650. }
  651. type pvKey struct {
  652. Labels map[string]string
  653. StorageClass string
  654. StorageClassParameters map[string]string
  655. }
  656. func (key *pvKey) GetStorageClass() string {
  657. return key.StorageClass
  658. }
  659. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  660. return &pvKey{
  661. Labels: pv.Labels,
  662. StorageClass: pv.Spec.StorageClassName,
  663. StorageClassParameters: parameters,
  664. }
  665. }
  666. func (key *pvKey) Features() string {
  667. // TODO: regional cluster pricing.
  668. storageClass := key.StorageClassParameters["type"]
  669. if storageClass == "pd-ssd" {
  670. storageClass = "ssd"
  671. } else if storageClass == "pd-standard" {
  672. storageClass = "pdstandard"
  673. }
  674. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  675. }
  676. type gcpKey struct {
  677. Labels map[string]string
  678. }
  679. func (gcp *GCP) GetKey(labels map[string]string) Key {
  680. return &gcpKey{
  681. Labels: labels,
  682. }
  683. }
  684. func (gcp *gcpKey) ID() string {
  685. return ""
  686. }
  687. func (gcp *gcpKey) GPUType() string {
  688. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  689. var usageType string
  690. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  691. usageType = "preemptible"
  692. } else {
  693. usageType = "ondemand"
  694. }
  695. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  696. return t + "," + usageType
  697. }
  698. return ""
  699. }
  700. // GetKey maps node labels to information needed to retrieve pricing data
  701. func (gcp *gcpKey) Features() string {
  702. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  703. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  704. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  705. } else if strings.HasPrefix(instanceType, "custom") {
  706. instanceType = "custom" // The suffix of custom does not matter
  707. }
  708. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  709. var usageType string
  710. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  711. usageType = "preemptible"
  712. } else {
  713. usageType = "ondemand"
  714. }
  715. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  716. return region + "," + instanceType + "," + usageType + "," + "gpu"
  717. }
  718. return region + "," + instanceType + "," + usageType
  719. }
  720. // AllNodePricing returns the GCP pricing objects stored
  721. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  722. gcp.DownloadPricingDataLock.RLock()
  723. defer gcp.DownloadPricingDataLock.RUnlock()
  724. return gcp.Pricing, nil
  725. }
  726. // NodePricing returns GCP pricing data for a single node
  727. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  728. gcp.DownloadPricingDataLock.RLock()
  729. defer gcp.DownloadPricingDataLock.RUnlock()
  730. if n, ok := gcp.Pricing[key.Features()]; ok {
  731. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  732. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  733. return n.Node, nil
  734. }
  735. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  736. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  737. }