main.go 9.7 KB

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