main.go 7.3 KB

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