main.go 6.1 KB

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