main.go 16 KB

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