main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. v1 "k8s.io/api/core/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "github.com/prometheus/client_golang/prometheus"
  19. "github.com/prometheus/client_golang/prometheus/promhttp"
  20. "k8s.io/client-go/kubernetes"
  21. "k8s.io/client-go/rest"
  22. )
  23. const (
  24. prometheusServerEndpointEnvVar = "PROMETHEUS_SERVER_ENDPOINT"
  25. )
  26. var (
  27. // gitCommit is set by the build system
  28. gitCommit string
  29. )
  30. type Accesses struct {
  31. PrometheusClient prometheusClient.Client
  32. KubeClientSet kubernetes.Interface
  33. Cloud costAnalyzerCloud.Provider
  34. CPUPriceRecorder *prometheus.GaugeVec
  35. RAMPriceRecorder *prometheus.GaugeVec
  36. PersistentVolumePriceRecorder *prometheus.GaugeVec
  37. GPUPriceRecorder *prometheus.GaugeVec
  38. NodeTotalPriceRecorder *prometheus.GaugeVec
  39. RAMAllocationRecorder *prometheus.GaugeVec
  40. CPUAllocationRecorder *prometheus.GaugeVec
  41. }
  42. type DataEnvelope struct {
  43. Code int `json:"code"`
  44. Status string `json:"status"`
  45. Data interface{} `json:"data"`
  46. Message string `json:"message,omitempty"`
  47. }
  48. func wrapData(data interface{}, err error) []byte {
  49. var resp []byte
  50. if err != nil {
  51. resp, _ = json.Marshal(&DataEnvelope{
  52. Code: 500,
  53. Status: "error",
  54. Message: err.Error(),
  55. Data: data,
  56. })
  57. } else {
  58. resp, _ = json.Marshal(&DataEnvelope{
  59. Code: 200,
  60. Status: "success",
  61. Data: data,
  62. })
  63. }
  64. return resp
  65. }
  66. // 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.
  67. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  68. w.Header().Set("Content-Type", "application/json")
  69. w.Header().Set("Access-Control-Allow-Origin", "*")
  70. err := a.Cloud.DownloadPricingData()
  71. w.Write(wrapData(nil, err))
  72. }
  73. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  74. w.Header().Set("Content-Type", "application/json")
  75. w.Header().Set("Access-Control-Allow-Origin", "*")
  76. window := r.URL.Query().Get("timeWindow")
  77. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, window)
  78. w.Write(wrapData(data, err))
  79. }
  80. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  81. w.Header().Set("Content-Type", "application/json")
  82. w.Header().Set("Access-Control-Allow-Origin", "*")
  83. start := r.URL.Query().Get("start")
  84. end := r.URL.Query().Get("end")
  85. window := r.URL.Query().Get("window")
  86. data, err := costModel.ComputeCostDataRange(a.PrometheusClient, a.KubeClientSet, a.Cloud, start, end, window)
  87. w.Write(wrapData(data, err))
  88. }
  89. func (a *Accesses) OutofClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  90. w.Header().Set("Content-Type", "application/json")
  91. w.Header().Set("Access-Control-Allow-Origin", "*")
  92. start := r.URL.Query().Get("start")
  93. end := r.URL.Query().Get("end")
  94. aggregator := r.URL.Query().Get("aggregator")
  95. data, err := a.Cloud.ExternalAllocations(start, end, aggregator)
  96. w.Write(wrapData(data, err))
  97. }
  98. func (p *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  99. w.Header().Set("Content-Type", "application/json")
  100. w.Header().Set("Access-Control-Allow-Origin", "*")
  101. data, err := p.Cloud.AllNodePricing()
  102. w.Write(wrapData(data, err))
  103. }
  104. func (p *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  105. w.Header().Set("Content-Type", "application/json")
  106. w.Header().Set("Access-Control-Allow-Origin", "*")
  107. data, err := p.Cloud.GetConfig()
  108. w.Write(wrapData(data, err))
  109. }
  110. func (p *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  111. w.Header().Set("Content-Type", "application/json")
  112. w.Header().Set("Access-Control-Allow-Origin", "*")
  113. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.SpotInfoUpdateType)
  114. if err != nil {
  115. w.Write(wrapData(data, err))
  116. return
  117. }
  118. w.Write(wrapData(data, err))
  119. err = p.Cloud.DownloadPricingData()
  120. if err != nil {
  121. klog.V(1).Infof("Error redownloading data on config update: %s", err.Error())
  122. }
  123. return
  124. }
  125. func (p *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  126. w.Header().Set("Content-Type", "application/json")
  127. w.Header().Set("Access-Control-Allow-Origin", "*")
  128. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.AthenaInfoUpdateType)
  129. if err != nil {
  130. w.Write(wrapData(data, err))
  131. return
  132. }
  133. w.Write(wrapData(data, err))
  134. return
  135. }
  136. func (p *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  137. w.Header().Set("Content-Type", "application/json")
  138. w.Header().Set("Access-Control-Allow-Origin", "*")
  139. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.BigqueryUpdateType)
  140. if err != nil {
  141. w.Write(wrapData(data, err))
  142. return
  143. }
  144. w.Write(wrapData(data, err))
  145. return
  146. }
  147. func (p *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  148. w.Header().Set("Content-Type", "application/json")
  149. w.Header().Set("Access-Control-Allow-Origin", "*")
  150. data, err := p.Cloud.UpdateConfig(r.Body, "")
  151. if err != nil {
  152. w.Write(wrapData(data, err))
  153. return
  154. }
  155. w.Write(wrapData(data, err))
  156. return
  157. }
  158. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  159. w.WriteHeader(200)
  160. w.Header().Set("Content-Length", "0")
  161. w.Header().Set("Content-Type", "text/plain")
  162. }
  163. func (a *Accesses) recordPrices() {
  164. go func() {
  165. for {
  166. klog.V(3).Info("Recording prices...")
  167. data, err := costModel.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "1m")
  168. if err != nil {
  169. klog.V(1).Info("Error in price recording: " + err.Error())
  170. // zero the for loop so the time.Sleep will still work
  171. data = map[string]*costModel.CostData{}
  172. }
  173. for _, costs := range data {
  174. nodeName := costs.NodeName
  175. node := costs.NodeData
  176. if node == nil {
  177. klog.V(3).Infof("Skipping Node \"%s\" due to missing Node Data costs", nodeName)
  178. continue
  179. }
  180. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  181. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  182. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  183. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  184. gpu, _ := strconv.ParseFloat(node.GPU, 64)
  185. gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64)
  186. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost
  187. if costs.PVCData != nil {
  188. for _, pvc := range costs.PVCData {
  189. pvCost, _ := strconv.ParseFloat(pvc.Volume.Cost, 64)
  190. a.PersistentVolumePriceRecorder.WithLabelValues(pvc.VolumeName, pvc.VolumeName).Set(pvCost)
  191. }
  192. }
  193. a.CPUPriceRecorder.WithLabelValues(nodeName, nodeName).Set(cpuCost)
  194. a.RAMPriceRecorder.WithLabelValues(nodeName, nodeName).Set(ramCost)
  195. a.GPUPriceRecorder.WithLabelValues(nodeName, nodeName).Set(gpuCost)
  196. a.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName).Set(totalCost)
  197. namespace := costs.Namespace
  198. podName := costs.PodName
  199. containerName := costs.Name
  200. if len(costs.RAMAllocation) > 0 {
  201. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.RAMAllocation[0].Value)
  202. }
  203. if len(costs.CPUAllocation) > 0 {
  204. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.CPUAllocation[0].Value)
  205. }
  206. storageClasses, _ := a.KubeClientSet.StorageV1().StorageClasses().List(metav1.ListOptions{})
  207. storageClassMap := make(map[string]map[string]string)
  208. for _, storageClass := range storageClasses.Items {
  209. params := storageClass.Parameters
  210. storageClassMap[storageClass.ObjectMeta.Name] = params
  211. }
  212. pvs, _ := a.KubeClientSet.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  213. for _, pv := range pvs.Items {
  214. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  215. if !ok {
  216. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  217. }
  218. cacPv := &costAnalyzerCloud.PV{
  219. Class: pv.Spec.StorageClassName,
  220. Region: pv.Labels[v1.LabelZoneRegion],
  221. Parameters: parameters,
  222. }
  223. costModel.GetPVCost(cacPv, &pv, a.Cloud)
  224. c, _ := strconv.ParseFloat(cacPv.Cost, 64)
  225. a.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name).Set(c)
  226. }
  227. }
  228. time.Sleep(time.Minute)
  229. }
  230. }()
  231. }
  232. func main() {
  233. klog.InitFlags(nil)
  234. flag.Set("v", "3")
  235. flag.Parse()
  236. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  237. address := os.Getenv(prometheusServerEndpointEnvVar)
  238. if address == "" {
  239. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  240. }
  241. pc := prometheusClient.Config{
  242. Address: address,
  243. }
  244. promCli, _ := prometheusClient.NewClient(pc)
  245. api := prometheusAPI.NewAPI(promCli)
  246. _, err := api.Config(context.Background())
  247. if err != nil {
  248. klog.Fatal("Failed to use Prometheus at " + address + " Error: " + err.Error())
  249. }
  250. klog.V(1).Info("Checked prometheus endpoint: " + address)
  251. // Kubernetes API setup
  252. kc, err := rest.InClusterConfig()
  253. if err != nil {
  254. panic(err.Error())
  255. }
  256. kubeClientset, err := kubernetes.NewForConfig(kc)
  257. if err != nil {
  258. panic(err.Error())
  259. }
  260. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  261. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  262. if err != nil {
  263. panic(err.Error())
  264. }
  265. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  266. Name: "node_cpu_hourly_cost",
  267. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  268. }, []string{"instance", "node"})
  269. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  270. Name: "node_ram_hourly_cost",
  271. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  272. }, []string{"instance", "node"})
  273. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  274. Name: "node_gpu_hourly_cost",
  275. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  276. }, []string{"instance", "node"})
  277. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  278. Name: "node_total_hourly_cost",
  279. Help: "node_total_hourly_cost Total node cost per hour",
  280. }, []string{"instance", "node"})
  281. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  282. Name: "pv_hourly_cost",
  283. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  284. }, []string{"volumename", "persistentvolume"})
  285. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  286. Name: "container_memory_allocation_bytes",
  287. Help: "container_memory_allocation_bytes Bytes of RAM used",
  288. }, []string{"namespace", "pod", "container", "instance", "node"})
  289. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  290. Name: "container_cpu_allocation",
  291. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  292. }, []string{"namespace", "pod", "container", "instance", "node"})
  293. prometheus.MustRegister(cpuGv)
  294. prometheus.MustRegister(ramGv)
  295. prometheus.MustRegister(gpuGv)
  296. prometheus.MustRegister(totalGv)
  297. prometheus.MustRegister(pvGv)
  298. prometheus.MustRegister(RAMAllocation)
  299. prometheus.MustRegister(CPUAllocation)
  300. a := Accesses{
  301. PrometheusClient: promCli,
  302. KubeClientSet: kubeClientset,
  303. Cloud: cloudProvider,
  304. CPUPriceRecorder: cpuGv,
  305. RAMPriceRecorder: ramGv,
  306. GPUPriceRecorder: gpuGv,
  307. NodeTotalPriceRecorder: totalGv,
  308. RAMAllocationRecorder: RAMAllocation,
  309. CPUAllocationRecorder: CPUAllocation,
  310. PersistentVolumePriceRecorder: pvGv,
  311. }
  312. err = a.Cloud.DownloadPricingData()
  313. if err != nil {
  314. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  315. }
  316. a.recordPrices()
  317. router := httprouter.New()
  318. router.GET("/costDataModel", a.CostDataModel)
  319. router.GET("/costDataModelRange", a.CostDataModelRange)
  320. router.GET("/outOfClusterCosts", a.OutofClusterCosts)
  321. router.GET("/allNodePricing", a.GetAllNodePricing)
  322. router.GET("/healthz", Healthz)
  323. router.GET("/getConfigs", a.GetConfigs)
  324. router.POST("/refreshPricing", a.RefreshPricingData)
  325. router.POST("/updateSpotInfoConfigs", a.UpdateSpotInfoConfigs)
  326. router.POST("/updateAthenaInfoConfigs", a.UpdateAthenaInfoConfigs)
  327. router.POST("/updateBigQueryInfoConfigs", a.UpdateBigQueryInfoConfigs)
  328. router.POST("/updateConfigByKey", a.UpdateConfigByKey)
  329. rootMux := http.NewServeMux()
  330. rootMux.Handle("/", router)
  331. rootMux.Handle("/metrics", promhttp.Handler())
  332. klog.Fatal(http.ListenAndServe(":9003", rootMux))
  333. }