gcpprovider.go 16 KB

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