main.go 11 KB

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