main.go 13 KB

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