gcpprovider.go 13 KB

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