gcpprovider.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package cloud
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "math"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "k8s.io/klog"
  13. "cloud.google.com/go/compute/metadata"
  14. "golang.org/x/oauth2"
  15. "golang.org/x/oauth2/google"
  16. compute "google.golang.org/api/compute/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/client-go/kubernetes"
  19. )
  20. type userAgentTransport struct {
  21. userAgent string
  22. base http.RoundTripper
  23. }
  24. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  25. req.Header.Set("User-Agent", t.userAgent)
  26. return t.base.RoundTrip(req)
  27. }
  28. // GCP implements a provider interface for GCP
  29. type GCP struct {
  30. Pricing map[string]*GCPPricing
  31. Clientset *kubernetes.Clientset
  32. APIKey string
  33. BaseCPUPrice string
  34. }
  35. // QuerySQL should query BigQuery for billing data for out of cluster costs. TODO: Implement.
  36. func (*GCP) QuerySQL(query string) ([]byte, error) {
  37. return nil, nil
  38. }
  39. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  40. func (*GCP) ClusterName() ([]byte, error) {
  41. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  42. userAgent: "kubecost",
  43. base: http.DefaultTransport,
  44. }})
  45. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  46. if err != nil {
  47. return nil, err
  48. }
  49. m := make(map[string]string)
  50. m["name"] = attribute
  51. m["provider"] = "GCP"
  52. return json.Marshal(m)
  53. }
  54. // AddServiceKey adds the service key as required for GetDisks
  55. func (*GCP) AddServiceKey(formValues url.Values) error {
  56. key := formValues.Get("key")
  57. k := []byte(key)
  58. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  59. }
  60. // 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.
  61. func (*GCP) GetDisks() ([]byte, error) {
  62. // metadata API setup
  63. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  64. userAgent: "kubecost",
  65. base: http.DefaultTransport,
  66. }})
  67. projID, err := metadataClient.ProjectID()
  68. if err != nil {
  69. return nil, err
  70. }
  71. client, err := google.DefaultClient(oauth2.NoContext,
  72. "https://www.googleapis.com/auth/compute.readonly")
  73. if err != nil {
  74. return nil, err
  75. }
  76. svc, err := compute.New(client)
  77. if err != nil {
  78. return nil, err
  79. }
  80. res, err := svc.Disks.AggregatedList(projID).Do()
  81. if err != nil {
  82. return nil, err
  83. }
  84. return json.Marshal(res)
  85. }
  86. // GCPPricing represents GCP pricing data for a SKU
  87. type GCPPricing struct {
  88. Name string `json:"name"`
  89. SKUID string `json:"skuId"`
  90. Description string `json:"description"`
  91. Category *GCPResourceInfo `json:"category"`
  92. ServiceRegions []string `json:"serviceRegions"`
  93. PricingInfo []*PricingInfo `json:"pricingInfo"`
  94. ServiceProviderName string `json:"serviceProviderName"`
  95. Node *Node `json:"node"`
  96. }
  97. // PricingInfo contains metadata about a cost.
  98. type PricingInfo struct {
  99. Summary string `json:"summary"`
  100. PricingExpression *PricingExpression `json:"pricingExpression"`
  101. CurrencyConversionRate int `json:"currencyConversionRate"`
  102. EffectiveTime string `json:""`
  103. }
  104. // PricingExpression contains metadata about a cost.
  105. type PricingExpression struct {
  106. UsageUnit string `json:"usageUnit"`
  107. UsageUnitDescription string `json:"usageUnitDescription"`
  108. BaseUnit string `json:"baseUnit"`
  109. BaseUnitConversionFactor int64 `json:"-"`
  110. DisplayQuantity int `json:"displayQuantity"`
  111. TieredRates []*TieredRates `json:"tieredRates"`
  112. }
  113. // TieredRates contain data about variable pricing.
  114. type TieredRates struct {
  115. StartUsageAmount int `json:"startUsageAmount"`
  116. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  117. }
  118. // UnitPriceInfo contains data about the actual price being charged.
  119. type UnitPriceInfo struct {
  120. CurrencyCode string `json:"currencyCode"`
  121. Units string `json:"units"`
  122. Nanos float64 `json:"nanos"`
  123. }
  124. // GCPResourceInfo contains metadata about the node.
  125. type GCPResourceInfo struct {
  126. ServiceDisplayName string `json:"serviceDisplayName"`
  127. ResourceFamily string `json:"resourceFamily"`
  128. ResourceGroup string `json:"resourceGroup"`
  129. UsageType string `json:"usageType"`
  130. }
  131. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]bool) (map[string]*GCPPricing, string) {
  132. gcpPricingList := make(map[string]*GCPPricing)
  133. var nextPageToken string
  134. dec := json.NewDecoder(r)
  135. for {
  136. t, err := dec.Token()
  137. if err == io.EOF {
  138. break
  139. }
  140. //fmt.Printf("%v \n", t)
  141. if t == "skus" {
  142. dec.Token() // [
  143. for dec.More() {
  144. product := &GCPPricing{}
  145. err := dec.Decode(&product)
  146. if err != nil {
  147. fmt.Printf("Error: " + err.Error())
  148. break
  149. }
  150. usageType := strings.ToLower(product.Category.UsageType)
  151. instanceType := strings.ToLower(product.Category.ResourceGroup)
  152. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  153. instanceType = "custom"
  154. }
  155. // instance.toLowerCase() === “f1micro”
  156. var partialCPU float64
  157. if strings.ToLower(instanceType) == "f1micro" {
  158. partialCPU = 0.2
  159. } else if strings.ToLower(instanceType) == "g1small" {
  160. partialCPU = 0.5
  161. }
  162. for _, sr := range product.ServiceRegions {
  163. region := sr
  164. candidateKey := region + "," + instanceType + "," + usageType
  165. if _, ok := inputKeys[candidateKey]; ok {
  166. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  167. var nanos float64
  168. if len(product.PricingInfo) > 0 {
  169. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  170. } else {
  171. continue
  172. }
  173. hourlyPrice := nanos * math.Pow10(-9)
  174. if hourlyPrice == 0 {
  175. continue
  176. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  177. if instanceType == "custom" {
  178. klog.V(2).Infof("RAM custom sku is: " + product.Name)
  179. }
  180. if _, ok := gcpPricingList[candidateKey]; ok {
  181. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  182. } else {
  183. product.Node = &Node{
  184. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  185. }
  186. if partialCPU != 0 {
  187. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  188. }
  189. product.Node.UsageType = usageType
  190. gcpPricingList[candidateKey] = product
  191. }
  192. break
  193. } else {
  194. if _, ok := gcpPricingList[candidateKey]; ok {
  195. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  196. } else {
  197. product.Node = &Node{
  198. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  199. }
  200. if partialCPU != 0 {
  201. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  202. }
  203. product.Node.UsageType = usageType
  204. gcpPricingList[candidateKey] = product
  205. }
  206. break
  207. }
  208. }
  209. }
  210. }
  211. }
  212. if t == "nextPageToken" {
  213. pageToken, err := dec.Token()
  214. if err != nil {
  215. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  216. break
  217. }
  218. if pageToken.(string) != "" {
  219. nextPageToken = pageToken.(string)
  220. } else {
  221. nextPageToken = "done"
  222. }
  223. }
  224. }
  225. return gcpPricingList, nextPageToken
  226. }
  227. func (gcp *GCP) parsePages(inputKeys map[string]bool) (map[string]*GCPPricing, error) {
  228. var pages []map[string]*GCPPricing
  229. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey //AIzaSyDXQPG_MHUEy9neR7stolq6l0ujXmjJlvk
  230. klog.V(2).Infof("URL: %s", url)
  231. var parsePagesHelper func(string) error
  232. parsePagesHelper = func(pageToken string) error {
  233. if pageToken == "done" {
  234. return nil
  235. } else if pageToken != "" {
  236. url = url + "&pageToken=" + pageToken
  237. }
  238. resp, err := http.Get(url)
  239. if err != nil {
  240. return err
  241. }
  242. page, token := gcp.parsePage(resp.Body, inputKeys)
  243. pages = append(pages, page)
  244. return parsePagesHelper(token)
  245. }
  246. err := parsePagesHelper("")
  247. returnPages := make(map[string]*GCPPricing)
  248. for _, page := range pages {
  249. for k, v := range page {
  250. if val, ok := returnPages[k]; ok { //keys may need to be merged
  251. if val.Node.RAMCost != "" && val.Node.VCPUCost == "" {
  252. val.Node.VCPUCost = v.Node.VCPUCost
  253. } else if val.Node.VCPUCost != "" && val.Node.RAMCost == "" {
  254. val.Node.RAMCost = v.Node.RAMCost
  255. } else {
  256. returnPages[k] = v
  257. }
  258. } else {
  259. returnPages[k] = v
  260. }
  261. }
  262. }
  263. return returnPages, err
  264. }
  265. // 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.
  266. func (gcp *GCP) DownloadPricingData() error {
  267. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  268. if err != nil {
  269. return err
  270. }
  271. inputkeys := make(map[string]bool)
  272. for _, n := range nodeList.Items {
  273. labels := n.GetObjectMeta().GetLabels()
  274. key := gcp.GetKey(labels)
  275. inputkeys[key] = true
  276. }
  277. pages, err := gcp.parsePages(inputkeys)
  278. if err != nil {
  279. return err
  280. }
  281. gcp.Pricing = pages
  282. c, err := GetDefaultPricingData("default.json")
  283. if err != nil {
  284. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  285. }
  286. gcp.BaseCPUPrice = c.CPU
  287. return nil
  288. }
  289. // GetKey maps node labels to information needed to retrieve pricing data
  290. func (gcp *GCP) GetKey(labels map[string]string) string {
  291. instanceType := strings.ToLower(strings.Join(strings.Split(labels["beta.kubernetes.io/instance-type"], "-")[:2], ""))
  292. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  293. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  294. } else if strings.HasPrefix(instanceType, "custom") {
  295. instanceType = "custom" // The suffix of custom does not matter
  296. }
  297. region := strings.ToLower(labels["failure-domain.beta.kubernetes.io/region"])
  298. var usageType string
  299. if t, ok := labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  300. usageType = "preemptible"
  301. } else {
  302. usageType = "ondemand"
  303. }
  304. return region + "," + instanceType + "," + usageType
  305. }
  306. // AllNodePricing returns the GCP pricing objects stored
  307. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  308. return gcp.Pricing, nil
  309. }
  310. // NodePricing returns GCP pricing data for a single node
  311. func (gcp *GCP) NodePricing(key string) (*Node, error) {
  312. if n, ok := gcp.Pricing[key]; ok {
  313. klog.V(2).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  314. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  315. return n.Node, nil
  316. }
  317. klog.V(1).Infof("Warning: no pricing data found for %s", key)
  318. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  319. }