main.go 8.2 KB

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