main.go 17 KB

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