gcpprovider.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. "regexp"
  12. "strconv"
  13. "strings"
  14. "k8s.io/klog"
  15. "cloud.google.com/go/bigquery"
  16. "cloud.google.com/go/compute/metadata"
  17. "golang.org/x/oauth2"
  18. "golang.org/x/oauth2/google"
  19. compute "google.golang.org/api/compute/v1"
  20. "google.golang.org/api/iterator"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/client-go/kubernetes"
  24. )
  25. type userAgentTransport struct {
  26. userAgent string
  27. base http.RoundTripper
  28. }
  29. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  30. req.Header.Set("User-Agent", t.userAgent)
  31. return t.base.RoundTrip(req)
  32. }
  33. // GCP implements a provider interface for GCP
  34. type GCP struct {
  35. Pricing map[string]*GCPPricing
  36. Clientset *kubernetes.Clientset
  37. APIKey string
  38. BaseCPUPrice string
  39. ProjectID string
  40. BillingDataDataset string
  41. }
  42. type gcpAllocation struct {
  43. Aggregator bigquery.NullString
  44. Environment bigquery.NullString
  45. Service string
  46. Cost float64
  47. }
  48. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  49. var aggregator string
  50. if gcpAlloc.Aggregator.Valid {
  51. aggregator = gcpAlloc.Aggregator.StringVal
  52. }
  53. var environment string
  54. if gcpAlloc.Environment.Valid {
  55. environment = gcpAlloc.Environment.StringVal
  56. }
  57. return &OutOfClusterAllocation{
  58. Aggregator: aggregator,
  59. Environment: environment,
  60. Service: gcpAlloc.Service,
  61. Cost: gcpAlloc.Cost,
  62. }
  63. }
  64. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  65. return nil, nil
  66. }
  67. func (gcp *GCP) UpdateConfig(r io.Reader) (*CustomPricing, error) {
  68. return nil, nil
  69. }
  70. func (gcp *GCP) ExternalAllocations(start string, end string) ([]*OutOfClusterAllocation, error) {
  71. // start, end formatted like: "2019-04-20 00:00:00"
  72. queryString := fmt.Sprintf(`SELECT
  73. service,
  74. labels.key as aggregator,
  75. labels.value as environment,
  76. SUM(cost) as cost
  77. FROM (SELECT
  78. service.description as service,
  79. labels,
  80. cost
  81. FROM %s
  82. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  83. LEFT JOIN UNNEST(labels) as labels
  84. 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"
  85. GROUP BY aggregator, environment, service;`, gcp.BillingDataDataset, start, end) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  86. klog.V(3).Infof("Querying \"%s\" with : %s", gcp.ProjectID, queryString)
  87. return gcp.QuerySQL(queryString)
  88. }
  89. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  90. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  91. ctx := context.Background()
  92. client, err := bigquery.NewClient(ctx, gcp.ProjectID) // For example, "guestbook-227502"
  93. if err != nil {
  94. return nil, err
  95. }
  96. q := client.Query(query)
  97. it, err := q.Read(ctx)
  98. if err != nil {
  99. return nil, err
  100. }
  101. var allocations []*OutOfClusterAllocation
  102. for {
  103. var a gcpAllocation
  104. err := it.Next(&a)
  105. if err == iterator.Done {
  106. break
  107. }
  108. if err != nil {
  109. return nil, err
  110. }
  111. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  112. }
  113. return allocations, nil
  114. }
  115. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  116. func (*GCP) ClusterName() ([]byte, error) {
  117. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  118. userAgent: "kubecost",
  119. base: http.DefaultTransport,
  120. }})
  121. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  122. if err != nil {
  123. return nil, err
  124. }
  125. m := make(map[string]string)
  126. m["name"] = attribute
  127. m["provider"] = "GCP"
  128. return json.Marshal(m)
  129. }
  130. // AddServiceKey adds the service key as required for GetDisks
  131. func (*GCP) AddServiceKey(formValues url.Values) error {
  132. key := formValues.Get("key")
  133. k := []byte(key)
  134. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  135. }
  136. // 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.
  137. func (*GCP) GetDisks() ([]byte, error) {
  138. // metadata API setup
  139. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  140. userAgent: "kubecost",
  141. base: http.DefaultTransport,
  142. }})
  143. projID, err := metadataClient.ProjectID()
  144. if err != nil {
  145. return nil, err
  146. }
  147. client, err := google.DefaultClient(oauth2.NoContext,
  148. "https://www.googleapis.com/auth/compute.readonly")
  149. if err != nil {
  150. return nil, err
  151. }
  152. svc, err := compute.New(client)
  153. if err != nil {
  154. return nil, err
  155. }
  156. res, err := svc.Disks.AggregatedList(projID).Do()
  157. if err != nil {
  158. return nil, err
  159. }
  160. return json.Marshal(res)
  161. }
  162. // GCPPricing represents GCP pricing data for a SKU
  163. type GCPPricing struct {
  164. Name string `json:"name"`
  165. SKUID string `json:"skuId"`
  166. Description string `json:"description"`
  167. Category *GCPResourceInfo `json:"category"`
  168. ServiceRegions []string `json:"serviceRegions"`
  169. PricingInfo []*PricingInfo `json:"pricingInfo"`
  170. ServiceProviderName string `json:"serviceProviderName"`
  171. Node *Node `json:"node"`
  172. }
  173. // PricingInfo contains metadata about a cost.
  174. type PricingInfo struct {
  175. Summary string `json:"summary"`
  176. PricingExpression *PricingExpression `json:"pricingExpression"`
  177. CurrencyConversionRate int `json:"currencyConversionRate"`
  178. EffectiveTime string `json:""`
  179. }
  180. // PricingExpression contains metadata about a cost.
  181. type PricingExpression struct {
  182. UsageUnit string `json:"usageUnit"`
  183. UsageUnitDescription string `json:"usageUnitDescription"`
  184. BaseUnit string `json:"baseUnit"`
  185. BaseUnitConversionFactor int64 `json:"-"`
  186. DisplayQuantity int `json:"displayQuantity"`
  187. TieredRates []*TieredRates `json:"tieredRates"`
  188. }
  189. // TieredRates contain data about variable pricing.
  190. type TieredRates struct {
  191. StartUsageAmount int `json:"startUsageAmount"`
  192. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  193. }
  194. // UnitPriceInfo contains data about the actual price being charged.
  195. type UnitPriceInfo struct {
  196. CurrencyCode string `json:"currencyCode"`
  197. Units string `json:"units"`
  198. Nanos float64 `json:"nanos"`
  199. }
  200. // GCPResourceInfo contains metadata about the node.
  201. type GCPResourceInfo struct {
  202. ServiceDisplayName string `json:"serviceDisplayName"`
  203. ResourceFamily string `json:"resourceFamily"`
  204. ResourceGroup string `json:"resourceGroup"`
  205. UsageType string `json:"usageType"`
  206. }
  207. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key) (map[string]*GCPPricing, string, error) {
  208. gcpPricingList := make(map[string]*GCPPricing)
  209. var nextPageToken string
  210. dec := json.NewDecoder(r)
  211. for {
  212. t, err := dec.Token()
  213. if err == io.EOF {
  214. break
  215. }
  216. if t == "skus" {
  217. _, err := dec.Token() // consumes [
  218. if err != nil {
  219. return nil, "", err
  220. }
  221. for dec.More() {
  222. product := &GCPPricing{}
  223. err := dec.Decode(&product)
  224. if err != nil {
  225. return nil, "", err
  226. }
  227. usageType := strings.ToLower(product.Category.UsageType)
  228. instanceType := strings.ToLower(product.Category.ResourceGroup)
  229. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  230. instanceType = "custom"
  231. }
  232. var partialCPU float64
  233. if strings.ToLower(instanceType) == "f1micro" {
  234. partialCPU = 0.2
  235. } else if strings.ToLower(instanceType) == "g1small" {
  236. partialCPU = 0.5
  237. }
  238. var gpuType string
  239. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  240. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  241. if matchnum == 1 {
  242. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  243. klog.V(3).Info("GPU TYPE FOUND: " + gpuType)
  244. }
  245. }
  246. for _, sr := range product.ServiceRegions {
  247. region := sr
  248. candidateKey := region + "," + instanceType + "," + usageType
  249. candidateKeyGPU := candidateKey + ",gpu"
  250. if gpuType != "" {
  251. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  252. var nanos float64
  253. if len(product.PricingInfo) > 0 {
  254. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  255. } else {
  256. continue
  257. }
  258. hourlyPrice := nanos * math.Pow10(-9)
  259. for k, key := range inputKeys {
  260. if key.GPUType() == gpuType {
  261. if region == strings.Split(k, ",")[0] {
  262. klog.V(3).Infof("MATCHED GPU TO NODE in region " + region)
  263. candidateKeyGPU = key.Features()
  264. if pl, ok := gcpPricingList[candidateKeyGPU]; ok {
  265. pl.Node.GPUName = gpuType
  266. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  267. pl.Node.GPU = "1"
  268. } else {
  269. product.Node = &Node{
  270. GPUName: gpuType,
  271. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  272. GPU: "1",
  273. }
  274. klog.V(3).Infof("Added data for " + candidateKeyGPU)
  275. gcpPricingList[candidateKeyGPU] = product
  276. }
  277. }
  278. }
  279. }
  280. } else {
  281. if _, ok := inputKeys[candidateKey]; ok {
  282. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  283. var nanos float64
  284. if len(product.PricingInfo) > 0 {
  285. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  286. } else {
  287. continue
  288. }
  289. hourlyPrice := nanos * math.Pow10(-9)
  290. if hourlyPrice == 0 {
  291. continue
  292. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  293. if instanceType == "custom" {
  294. klog.V(2).Infof("RAM custom sku is: " + product.Name)
  295. }
  296. if _, ok := gcpPricingList[candidateKey]; ok {
  297. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  298. } else {
  299. product.Node = &Node{
  300. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  301. }
  302. if partialCPU != 0 {
  303. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  304. }
  305. product.Node.UsageType = usageType
  306. gcpPricingList[candidateKey] = product
  307. }
  308. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  309. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  310. } else {
  311. product.Node = &Node{
  312. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  313. }
  314. if partialCPU != 0 {
  315. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  316. }
  317. product.Node.UsageType = usageType
  318. gcpPricingList[candidateKeyGPU] = product
  319. }
  320. break
  321. } else {
  322. if _, ok := gcpPricingList[candidateKey]; ok {
  323. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  324. } else {
  325. product.Node = &Node{
  326. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  327. }
  328. if partialCPU != 0 {
  329. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  330. }
  331. product.Node.UsageType = usageType
  332. gcpPricingList[candidateKey] = product
  333. }
  334. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  335. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  336. } else {
  337. product.Node = &Node{
  338. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  339. }
  340. if partialCPU != 0 {
  341. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  342. }
  343. product.Node.UsageType = usageType
  344. gcpPricingList[candidateKeyGPU] = product
  345. }
  346. break
  347. }
  348. }
  349. }
  350. }
  351. }
  352. }
  353. if t == "nextPageToken" {
  354. pageToken, err := dec.Token()
  355. if err != nil {
  356. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  357. return nil, "", err
  358. }
  359. if pageToken.(string) != "" {
  360. nextPageToken = pageToken.(string)
  361. } else {
  362. nextPageToken = "done"
  363. }
  364. }
  365. }
  366. return gcpPricingList, nextPageToken, nil
  367. }
  368. func (gcp *GCP) parsePages(inputKeys map[string]Key) (map[string]*GCPPricing, error) {
  369. var pages []map[string]*GCPPricing
  370. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  371. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  372. var parsePagesHelper func(string) error
  373. parsePagesHelper = func(pageToken string) error {
  374. if pageToken == "done" {
  375. return nil
  376. } else if pageToken != "" {
  377. url = url + "&pageToken=" + pageToken
  378. }
  379. resp, err := http.Get(url)
  380. if err != nil {
  381. return err
  382. }
  383. page, token, err := gcp.parsePage(resp.Body, inputKeys)
  384. if err != nil {
  385. return err
  386. }
  387. pages = append(pages, page)
  388. return parsePagesHelper(token)
  389. }
  390. err := parsePagesHelper("")
  391. if err != nil {
  392. return nil, err
  393. }
  394. returnPages := make(map[string]*GCPPricing)
  395. for _, page := range pages {
  396. for k, v := range page {
  397. if val, ok := returnPages[k]; ok { //keys may need to be merged
  398. if val.Node.RAMCost != "" && val.Node.VCPUCost == "" {
  399. val.Node.VCPUCost = v.Node.VCPUCost
  400. } else if val.Node.VCPUCost != "" && val.Node.RAMCost == "" {
  401. val.Node.RAMCost = v.Node.RAMCost
  402. } else {
  403. returnPages[k] = v
  404. }
  405. } else {
  406. returnPages[k] = v
  407. }
  408. }
  409. }
  410. return returnPages, err
  411. }
  412. // 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.
  413. func (gcp *GCP) DownloadPricingData() error {
  414. c, err := GetDefaultPricingData("gcp.json")
  415. if err != nil {
  416. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  417. }
  418. gcp.BaseCPUPrice = c.CPU
  419. gcp.ProjectID = c.ProjectID
  420. gcp.BillingDataDataset = c.BillingDataDataset
  421. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  422. if err != nil {
  423. return err
  424. }
  425. inputkeys := make(map[string]Key)
  426. for _, n := range nodeList.Items {
  427. labels := n.GetObjectMeta().GetLabels()
  428. key := gcp.GetKey(labels)
  429. inputkeys[key.Features()] = key
  430. }
  431. pages, err := gcp.parsePages(inputkeys)
  432. if err != nil {
  433. return err
  434. }
  435. gcp.Pricing = pages
  436. return nil
  437. }
  438. type gcpKey struct {
  439. Labels map[string]string
  440. }
  441. func (gcp *GCP) GetKey(labels map[string]string) Key {
  442. return &gcpKey{
  443. Labels: labels,
  444. }
  445. }
  446. func (gcp *gcpKey) ID() string {
  447. return ""
  448. }
  449. func (gcp *gcpKey) GPUType() string {
  450. if t, ok := gcp.Labels["cloud.google.com/gke-accelerator"]; ok {
  451. klog.V(3).Infof("GPU of type: \"%s\" found", t)
  452. return t
  453. }
  454. return ""
  455. }
  456. // GetKey maps node labels to information needed to retrieve pricing data
  457. func (gcp *gcpKey) Features() string {
  458. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  459. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  460. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  461. } else if strings.HasPrefix(instanceType, "custom") {
  462. instanceType = "custom" // The suffix of custom does not matter
  463. }
  464. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  465. var usageType string
  466. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  467. usageType = "preemptible"
  468. } else {
  469. usageType = "ondemand"
  470. }
  471. if _, ok := gcp.Labels["cloud.google.com/gke-accelerator"]; ok {
  472. return region + "," + instanceType + "," + usageType + "," + "gpu"
  473. }
  474. return region + "," + instanceType + "," + usageType
  475. }
  476. // AllNodePricing returns the GCP pricing objects stored
  477. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  478. return gcp.Pricing, nil
  479. }
  480. // NodePricing returns GCP pricing data for a single node
  481. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  482. if n, ok := gcp.Pricing[key.Features()]; ok {
  483. klog.V(2).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  484. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  485. return n.Node, nil
  486. }
  487. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  488. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  489. }