main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "log"
  6. "net/http"
  7. "os"
  8. "strconv"
  9. "time"
  10. "github.com/julienschmidt/httprouter"
  11. costAnalyzerCloud "github.com/kubecost/cost-model/cloud"
  12. costModel "github.com/kubecost/cost-model/costmodel"
  13. prometheusClient "github.com/prometheus/client_golang/api"
  14. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  15. "github.com/prometheus/client_golang/prometheus"
  16. "github.com/prometheus/client_golang/prometheus/promhttp"
  17. "k8s.io/client-go/kubernetes"
  18. "k8s.io/client-go/rest"
  19. )
  20. type Accesses struct {
  21. PrometheusClient prometheusClient.Client
  22. KubeClientSet *kubernetes.Clientset
  23. Cloud costAnalyzerCloud.Provider
  24. CPUPriceRecorder *prometheus.GaugeVec
  25. RAMPriceRecorder *prometheus.GaugeVec
  26. NodeTotalPriceRecorder *prometheus.GaugeVec
  27. }
  28. type DataEnvelope struct {
  29. Code int `json:"code"`
  30. Status string `json:"status"`
  31. Data interface{} `json:"data"`
  32. Message string `json:"message,omitempty"`
  33. }
  34. func wrapData(data interface{}, err error) []byte {
  35. var resp []byte
  36. if err != nil {
  37. resp, _ = json.Marshal(&DataEnvelope{
  38. Code: 500,
  39. Status: "error",
  40. Message: err.Error(),
  41. Data: data,
  42. })
  43. } else {
  44. resp, _ = json.Marshal(&DataEnvelope{
  45. Code: 200,
  46. Status: "success",
  47. Data: data,
  48. })
  49. }
  50. return resp
  51. }
  52. // RefreshPricingData needs to be called when a new node joins the fleet, since we cache the relevant subsets of pricing data to avoid storing the whole thing.
  53. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  54. w.Header().Set("Content-Type", "application/json")
  55. w.Header().Set("Access-Control-Allow-Origin", "*")
  56. err := a.Cloud.DownloadPricingData()
  57. w.Write(wrapData(nil, err))
  58. }
  59. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  60. w.Header().Set("Content-Type", "application/json")
  61. w.Header().Set("Access-Control-Allow-Origin", "*")
  62. window := r.URL.Query().Get("timeWindow")
  63. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, window)
  64. w.Write(wrapData(data, err))
  65. }
  66. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  67. w.Header().Set("Content-Type", "application/json")
  68. w.Header().Set("Access-Control-Allow-Origin", "*")
  69. start := r.URL.Query().Get("start")
  70. end := r.URL.Query().Get("end")
  71. window := r.URL.Query().Get("window")
  72. data, err := costModel.ComputeCostDataRange(a.PrometheusClient, a.KubeClientSet, a.Cloud, start, end, window)
  73. w.Write(wrapData(data, err))
  74. }
  75. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  76. w.WriteHeader(200)
  77. w.Header().Set("Content-Length", "0")
  78. w.Header().Set("Content-Type", "text/plain")
  79. }
  80. func (a *Accesses) recordPrices() {
  81. go func() {
  82. for {
  83. log.Print("Recording prices...")
  84. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "1h")
  85. if err != nil {
  86. log.Printf("Error in price recording: " + err.Error())
  87. }
  88. for _, costs := range data {
  89. nodeName := costs.NodeName
  90. node := costs.NodeData
  91. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  92. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  93. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  94. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  95. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024)
  96. a.CPUPriceRecorder.WithLabelValues(nodeName).Set(cpuCost)
  97. a.RAMPriceRecorder.WithLabelValues(nodeName).Set(ramCost)
  98. a.NodeTotalPriceRecorder.WithLabelValues(nodeName).Set(totalCost)
  99. }
  100. time.Sleep(time.Minute)
  101. }
  102. }()
  103. }
  104. func main() {
  105. address := os.Getenv("PROMETHEUS_SERVER_ENDPOINT")
  106. if address == "" {
  107. log.Fatal("No address for prometheus set. Aborting.")
  108. }
  109. pc := prometheusClient.Config{
  110. Address: address,
  111. }
  112. promCli, _ := prometheusClient.NewClient(pc)
  113. api := prometheusAPI.NewAPI(promCli)
  114. _, err := api.Config(context.Background())
  115. if err != nil {
  116. log.Fatal("Failed to use Prometheus at " + address + " Error: " + err.Error())
  117. }
  118. log.Printf("Checked prometheus endpoint: " + address)
  119. // Kubernetes API setup
  120. kc, err := rest.InClusterConfig()
  121. if err != nil {
  122. panic(err.Error())
  123. }
  124. kubeClientset, err := kubernetes.NewForConfig(kc)
  125. if err != nil {
  126. panic(err.Error())
  127. }
  128. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  129. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  130. if err != nil {
  131. panic(err.Error())
  132. }
  133. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  134. Name: "node_cpu_hourly_cost",
  135. Help: "node_cpu_hourly_cost cost for each cpu on this node",
  136. }, []string{"instance"})
  137. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  138. Name: "node_ram_hourly_cost",
  139. Help: "node_ram_hourly_cost cost for each gb of ram on this node",
  140. }, []string{"instance"})
  141. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  142. Name: "node_total_hourly_cost",
  143. Help: "node_total_hourly_cost Total node cost per hour",
  144. }, []string{"instance"})
  145. prometheus.MustRegister(cpuGv)
  146. prometheus.MustRegister(ramGv)
  147. prometheus.MustRegister(totalGv)
  148. a := Accesses{
  149. PrometheusClient: promCli,
  150. KubeClientSet: kubeClientset,
  151. Cloud: cloudProvider,
  152. CPUPriceRecorder: cpuGv,
  153. RAMPriceRecorder: ramGv,
  154. NodeTotalPriceRecorder: totalGv,
  155. }
  156. err = a.Cloud.DownloadPricingData()
  157. if err != nil {
  158. log.Printf("Failed to download pricing data: " + err.Error())
  159. }
  160. a.recordPrices()
  161. router := httprouter.New()
  162. router.GET("/costDataModel", a.CostDataModel)
  163. router.GET("/costDataModelRange", a.CostDataModelRange)
  164. router.GET("/healthz", Healthz)
  165. router.POST("/refreshPricing", a.RefreshPricingData)
  166. rootMux := http.NewServeMux()
  167. rootMux.Handle("/", router)
  168. rootMux.Handle("/metrics", promhttp.Handler())
  169. log.Fatal(http.ListenAndServe(":9003", rootMux))
  170. }