main.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. const (
  22. prometheusServerEndpointEnvVar = "PROMETHEUS_SERVER_ENDPOINT"
  23. )
  24. var (
  25. // gitCommit is set by the build system
  26. gitCommit string
  27. )
  28. type Accesses struct {
  29. PrometheusClient prometheusClient.Client
  30. KubeClientSet kubernetes.Interface
  31. Cloud costAnalyzerCloud.Provider
  32. CPUPriceRecorder *prometheus.GaugeVec
  33. RAMPriceRecorder *prometheus.GaugeVec
  34. NodeTotalPriceRecorder *prometheus.GaugeVec
  35. RAMAllocationRecorder *prometheus.GaugeVec
  36. CPUAllocationRecorder *prometheus.GaugeVec
  37. }
  38. type DataEnvelope struct {
  39. Code int `json:"code"`
  40. Status string `json:"status"`
  41. Data interface{} `json:"data"`
  42. Message string `json:"message,omitempty"`
  43. }
  44. func wrapData(data interface{}, err error) []byte {
  45. var resp []byte
  46. if err != nil {
  47. resp, _ = json.Marshal(&DataEnvelope{
  48. Code: 500,
  49. Status: "error",
  50. Message: err.Error(),
  51. Data: data,
  52. })
  53. } else {
  54. resp, _ = json.Marshal(&DataEnvelope{
  55. Code: 200,
  56. Status: "success",
  57. Data: data,
  58. })
  59. }
  60. return resp
  61. }
  62. // 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.
  63. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  64. w.Header().Set("Content-Type", "application/json")
  65. w.Header().Set("Access-Control-Allow-Origin", "*")
  66. err := a.Cloud.DownloadPricingData()
  67. w.Write(wrapData(nil, err))
  68. }
  69. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  70. w.Header().Set("Content-Type", "application/json")
  71. w.Header().Set("Access-Control-Allow-Origin", "*")
  72. window := r.URL.Query().Get("timeWindow")
  73. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, window)
  74. w.Write(wrapData(data, err))
  75. }
  76. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  77. w.Header().Set("Content-Type", "application/json")
  78. w.Header().Set("Access-Control-Allow-Origin", "*")
  79. start := r.URL.Query().Get("start")
  80. end := r.URL.Query().Get("end")
  81. window := r.URL.Query().Get("window")
  82. data, err := costModel.ComputeCostDataRange(a.PrometheusClient, a.KubeClientSet, a.Cloud, start, end, window)
  83. w.Write(wrapData(data, err))
  84. }
  85. func (p *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  86. w.Header().Set("Content-Type", "application/json")
  87. w.Header().Set("Access-Control-Allow-Origin", "*")
  88. data, err := p.Cloud.AllNodePricing()
  89. w.Write(wrapData(data, err))
  90. }
  91. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  92. w.WriteHeader(200)
  93. w.Header().Set("Content-Length", "0")
  94. w.Header().Set("Content-Type", "text/plain")
  95. }
  96. func (a *Accesses) recordPrices() {
  97. go func() {
  98. for {
  99. klog.V(3).Info("Recording prices...")
  100. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "1m")
  101. if err != nil {
  102. klog.V(1).Info("Error in price recording: " + err.Error())
  103. // zero the for loop so the time.Sleep will still work
  104. data = map[string]*costModel.CostData{}
  105. }
  106. for _, costs := range data {
  107. nodeName := costs.NodeName
  108. node := costs.NodeData
  109. if node == nil {
  110. klog.V(3).Infof("Skipping Node \"%s\" due to missing Node Data costs", nodeName)
  111. continue
  112. }
  113. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  114. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  115. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  116. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  117. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024)
  118. a.CPUPriceRecorder.WithLabelValues(nodeName).Set(cpuCost)
  119. a.RAMPriceRecorder.WithLabelValues(nodeName).Set(ramCost)
  120. a.NodeTotalPriceRecorder.WithLabelValues(nodeName).Set(totalCost)
  121. namespace := costs.Namespace
  122. podName := costs.PodName
  123. containerName := costs.Name
  124. if len(costs.RAMAllocation) > 0 {
  125. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName).Set(costs.RAMAllocation[0].Value)
  126. }
  127. if len(costs.CPUAllocation) > 0 {
  128. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName).Set(costs.CPUAllocation[0].Value)
  129. }
  130. }
  131. time.Sleep(time.Minute)
  132. }
  133. }()
  134. }
  135. func main() {
  136. klog.InitFlags(nil)
  137. flag.Set("v", "3")
  138. flag.Parse()
  139. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  140. address := os.Getenv(prometheusServerEndpointEnvVar)
  141. if address == "" {
  142. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  143. }
  144. pc := prometheusClient.Config{
  145. Address: address,
  146. }
  147. promCli, _ := prometheusClient.NewClient(pc)
  148. api := prometheusAPI.NewAPI(promCli)
  149. _, err := api.Config(context.Background())
  150. if err != nil {
  151. klog.Fatal("Failed to use Prometheus at " + address + " Error: " + err.Error())
  152. }
  153. klog.V(1).Info("Checked prometheus endpoint: " + address)
  154. // Kubernetes API setup
  155. kc, err := rest.InClusterConfig()
  156. if err != nil {
  157. panic(err.Error())
  158. }
  159. kubeClientset, err := kubernetes.NewForConfig(kc)
  160. if err != nil {
  161. panic(err.Error())
  162. }
  163. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  164. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  165. if err != nil {
  166. panic(err.Error())
  167. }
  168. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  169. Name: "node_cpu_hourly_cost",
  170. Help: "node_cpu_hourly_cost cost for each cpu on this node",
  171. }, []string{"instance"})
  172. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  173. Name: "node_ram_hourly_cost",
  174. Help: "node_ram_hourly_cost cost for each gb of ram on this node",
  175. }, []string{"instance"})
  176. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  177. Name: "node_total_hourly_cost",
  178. Help: "node_total_hourly_cost Total node cost per hour",
  179. }, []string{"instance"})
  180. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  181. Name: "container_memory_allocation_bytes",
  182. Help: "container_memory_allocation_bytes Bytes of RAM used",
  183. }, []string{"namespace", "pod", "container", "instance"})
  184. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  185. Name: "container_cpu_allocation",
  186. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  187. }, []string{"namespace", "pod", "container", "instance"})
  188. prometheus.MustRegister(cpuGv)
  189. prometheus.MustRegister(ramGv)
  190. prometheus.MustRegister(totalGv)
  191. prometheus.MustRegister(RAMAllocation)
  192. prometheus.MustRegister(CPUAllocation)
  193. a := Accesses{
  194. PrometheusClient: promCli,
  195. KubeClientSet: kubeClientset,
  196. Cloud: cloudProvider,
  197. CPUPriceRecorder: cpuGv,
  198. RAMPriceRecorder: ramGv,
  199. NodeTotalPriceRecorder: totalGv,
  200. RAMAllocationRecorder: RAMAllocation,
  201. CPUAllocationRecorder: CPUAllocation,
  202. }
  203. err = a.Cloud.DownloadPricingData()
  204. if err != nil {
  205. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  206. }
  207. a.recordPrices()
  208. router := httprouter.New()
  209. router.GET("/costDataModel", a.CostDataModel)
  210. router.GET("/costDataModelRange", a.CostDataModelRange)
  211. router.GET("/allNodePricing", a.GetAllNodePricing)
  212. router.GET("/healthz", Healthz)
  213. router.POST("/refreshPricing", a.RefreshPricingData)
  214. rootMux := http.NewServeMux()
  215. rootMux.Handle("/", router)
  216. rootMux.Handle("/metrics", promhttp.Handler())
  217. klog.Fatal(http.ListenAndServe(":9003", rootMux))
  218. }