2
0

gcpprovider.go 11 KB

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