main.go 21 KB

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