main.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 (a *Accesses) OutofClusterCosts(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. start := r.URL.Query().Get("start")
  89. end := r.URL.Query().Get("end")
  90. data, err := a.Cloud.ExternalAllocations(start, end)
  91. w.Write(wrapData(data, err))
  92. }
  93. func (p *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  94. w.Header().Set("Content-Type", "application/json")
  95. w.Header().Set("Access-Control-Allow-Origin", "*")
  96. data, err := p.Cloud.AllNodePricing()
  97. w.Write(wrapData(data, err))
  98. }
  99. func (p *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  100. w.Header().Set("Content-Type", "application/json")
  101. w.Header().Set("Access-Control-Allow-Origin", "*")
  102. data, err := p.Cloud.GetConfig()
  103. w.Write(wrapData(data, err))
  104. }
  105. func (p *Accesses) UpdateConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  106. w.Header().Set("Content-Type", "application/json")
  107. w.Header().Set("Access-Control-Allow-Origin", "*")
  108. data, err := p.Cloud.UpdateConfig(r.Body)
  109. if err != nil {
  110. w.Write(wrapData(data, err))
  111. return
  112. }
  113. w.Write(wrapData(data, err))
  114. err = p.Cloud.DownloadPricingData()
  115. if err != nil {
  116. klog.V(1).Infof("Error redownloading data on config update")
  117. }
  118. return
  119. }
  120. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  121. w.WriteHeader(200)
  122. w.Header().Set("Content-Length", "0")
  123. w.Header().Set("Content-Type", "text/plain")
  124. }
  125. func (a *Accesses) recordPrices() {
  126. go func() {
  127. for {
  128. klog.V(3).Info("Recording prices...")
  129. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "1m")
  130. if err != nil {
  131. klog.V(1).Info("Error in price recording: " + err.Error())
  132. // zero the for loop so the time.Sleep will still work
  133. data = map[string]*costModel.CostData{}
  134. }
  135. for _, costs := range data {
  136. nodeName := costs.NodeName
  137. node := costs.NodeData
  138. if node == nil {
  139. klog.V(3).Infof("Skipping Node \"%s\" due to missing Node Data costs", nodeName)
  140. continue
  141. }
  142. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  143. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  144. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  145. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  146. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024)
  147. a.CPUPriceRecorder.WithLabelValues(nodeName).Set(cpuCost)
  148. a.RAMPriceRecorder.WithLabelValues(nodeName).Set(ramCost)
  149. a.NodeTotalPriceRecorder.WithLabelValues(nodeName).Set(totalCost)
  150. namespace := costs.Namespace
  151. podName := costs.PodName
  152. containerName := costs.Name
  153. if len(costs.RAMAllocation) > 0 {
  154. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName).Set(costs.RAMAllocation[0].Value)
  155. }
  156. if len(costs.CPUAllocation) > 0 {
  157. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName).Set(costs.CPUAllocation[0].Value)
  158. }
  159. }
  160. time.Sleep(time.Minute)
  161. }
  162. }()
  163. }
  164. func main() {
  165. klog.InitFlags(nil)
  166. flag.Set("v", "3")
  167. flag.Parse()
  168. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  169. address := os.Getenv(prometheusServerEndpointEnvVar)
  170. if address == "" {
  171. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  172. }
  173. pc := prometheusClient.Config{
  174. Address: address,
  175. }
  176. promCli, _ := prometheusClient.NewClient(pc)
  177. api := prometheusAPI.NewAPI(promCli)
  178. _, err := api.Config(context.Background())
  179. if err != nil {
  180. klog.Fatal("Failed to use Prometheus at " + address + " Error: " + err.Error())
  181. }
  182. klog.V(1).Info("Checked prometheus endpoint: " + address)
  183. // Kubernetes API setup
  184. kc, err := rest.InClusterConfig()
  185. if err != nil {
  186. panic(err.Error())
  187. }
  188. kubeClientset, err := kubernetes.NewForConfig(kc)
  189. if err != nil {
  190. panic(err.Error())
  191. }
  192. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  193. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  194. if err != nil {
  195. panic(err.Error())
  196. }
  197. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  198. Name: "node_cpu_hourly_cost",
  199. Help: "node_cpu_hourly_cost cost for each cpu on this node",
  200. }, []string{"instance"})
  201. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  202. Name: "node_ram_hourly_cost",
  203. Help: "node_ram_hourly_cost cost for each gb of ram on this node",
  204. }, []string{"instance"})
  205. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  206. Name: "node_total_hourly_cost",
  207. Help: "node_total_hourly_cost Total node cost per hour",
  208. }, []string{"instance"})
  209. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  210. Name: "container_memory_allocation_bytes",
  211. Help: "container_memory_allocation_bytes Bytes of RAM used",
  212. }, []string{"namespace", "pod", "container", "instance"})
  213. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  214. Name: "container_cpu_allocation",
  215. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  216. }, []string{"namespace", "pod", "container", "instance"})
  217. prometheus.MustRegister(cpuGv)
  218. prometheus.MustRegister(ramGv)
  219. prometheus.MustRegister(totalGv)
  220. prometheus.MustRegister(RAMAllocation)
  221. prometheus.MustRegister(CPUAllocation)
  222. a := Accesses{
  223. PrometheusClient: promCli,
  224. KubeClientSet: kubeClientset,
  225. Cloud: cloudProvider,
  226. CPUPriceRecorder: cpuGv,
  227. RAMPriceRecorder: ramGv,
  228. NodeTotalPriceRecorder: totalGv,
  229. RAMAllocationRecorder: RAMAllocation,
  230. CPUAllocationRecorder: CPUAllocation,
  231. }
  232. err = a.Cloud.DownloadPricingData()
  233. if err != nil {
  234. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  235. }
  236. a.recordPrices()
  237. router := httprouter.New()
  238. router.GET("/costDataModel", a.CostDataModel)
  239. router.GET("/costDataModelRange", a.CostDataModelRange)
  240. router.GET("/outOfClusterCosts", a.OutofClusterCosts)
  241. router.GET("/allNodePricing", a.GetAllNodePricing)
  242. router.GET("/healthz", Healthz)
  243. router.GET("/getConfigs", a.GetConfigs)
  244. router.POST("/refreshPricing", a.RefreshPricingData)
  245. router.POST("/updateConfigs", a.UpdateConfigs)
  246. rootMux := http.NewServeMux()
  247. rootMux.Handle("/", router)
  248. rootMux.Handle("/metrics", promhttp.Handler())
  249. klog.Fatal(http.ListenAndServe(":9003", rootMux))
  250. }