main.go 7.6 KB

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