main.go 13 KB

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