main.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // zero the for loop so the time.Sleep will still work
  88. data = map[string]*costModel.CostData{}
  89. }
  90. for _, costs := range data {
  91. nodeName := costs.NodeName
  92. node := costs.NodeData
  93. if node == nil {
  94. log.Printf("Skipping Node \"%s\" due to missing Node Data costs", nodeName)
  95. continue
  96. }
  97. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  98. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  99. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  100. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  101. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024)
  102. a.CPUPriceRecorder.WithLabelValues(nodeName).Set(cpuCost)
  103. a.RAMPriceRecorder.WithLabelValues(nodeName).Set(ramCost)
  104. a.NodeTotalPriceRecorder.WithLabelValues(nodeName).Set(totalCost)
  105. }
  106. time.Sleep(time.Minute)
  107. }
  108. }()
  109. }
  110. func main() {
  111. address := os.Getenv("PROMETHEUS_SERVER_ENDPOINT")
  112. if address == "" {
  113. log.Fatal("No address for prometheus set. Aborting.")
  114. }
  115. pc := prometheusClient.Config{
  116. Address: address,
  117. }
  118. promCli, _ := prometheusClient.NewClient(pc)
  119. api := prometheusAPI.NewAPI(promCli)
  120. _, err := api.Config(context.Background())
  121. if err != nil {
  122. log.Fatal("Failed to use Prometheus at " + address + " Error: " + err.Error())
  123. }
  124. log.Printf("Checked prometheus endpoint: " + address)
  125. // Kubernetes API setup
  126. kc, err := rest.InClusterConfig()
  127. if err != nil {
  128. panic(err.Error())
  129. }
  130. kubeClientset, err := kubernetes.NewForConfig(kc)
  131. if err != nil {
  132. panic(err.Error())
  133. }
  134. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  135. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  136. if err != nil {
  137. panic(err.Error())
  138. }
  139. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  140. Name: "node_cpu_hourly_cost",
  141. Help: "node_cpu_hourly_cost cost for each cpu on this node",
  142. }, []string{"instance"})
  143. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  144. Name: "node_ram_hourly_cost",
  145. Help: "node_ram_hourly_cost cost for each gb of ram on this node",
  146. }, []string{"instance"})
  147. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  148. Name: "node_total_hourly_cost",
  149. Help: "node_total_hourly_cost Total node cost per hour",
  150. }, []string{"instance"})
  151. prometheus.MustRegister(cpuGv)
  152. prometheus.MustRegister(ramGv)
  153. prometheus.MustRegister(totalGv)
  154. a := Accesses{
  155. PrometheusClient: promCli,
  156. KubeClientSet: kubeClientset,
  157. Cloud: cloudProvider,
  158. CPUPriceRecorder: cpuGv,
  159. RAMPriceRecorder: ramGv,
  160. NodeTotalPriceRecorder: totalGv,
  161. }
  162. err = a.Cloud.DownloadPricingData()
  163. if err != nil {
  164. log.Printf("Failed to download pricing data: " + err.Error())
  165. }
  166. a.recordPrices()
  167. router := httprouter.New()
  168. router.GET("/costDataModel", a.CostDataModel)
  169. router.GET("/costDataModelRange", a.CostDataModelRange)
  170. router.GET("/healthz", Healthz)
  171. router.POST("/refreshPricing", a.RefreshPricingData)
  172. rootMux := http.NewServeMux()
  173. rootMux.Handle("/", router)
  174. rootMux.Handle("/metrics", promhttp.Handler())
  175. log.Fatal(http.ListenAndServe(":9003", rootMux))
  176. }