gcpprovider.go 13 KB

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