main.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. RAMAllocSeen := make(map[string]string)
  271. CPUAllocSeen := make(map[string]string)
  272. GPUAllocSeen := make(map[string]string)
  273. ContainerUptimeSeen := make(map[string]string)
  274. CPUPriceSeen := make(map[string]string)
  275. RAMPriceSeen := make(map[string]string)
  276. PVPriceSeen := make(map[string]string)
  277. GPUPriceSeen := make(map[string]string)
  278. TotalPriceSeen := make(map[string]string)
  279. for {
  280. klog.V(4).Info("Recording prices...")
  281. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "2m", "", "")
  282. if err != nil {
  283. klog.V(1).Info("Error in price recording: " + err.Error())
  284. // zero the for loop so the time.Sleep will still work
  285. data = map[string]*costModel.CostData{}
  286. }
  287. prometheus.Unregister(a.RAMAllocationRecorder)
  288. prometheus.Unregister(a.CPUAllocationRecorder)
  289. prometheus.Unregister(a.GPUAllocationRecorder)
  290. prometheus.Unregister(a.ContainerUptimeRecorder)
  291. prometheus.Unregister(a.CPUPriceRecorder)
  292. prometheus.Unregister(a.RAMPriceRecorder)
  293. prometheus.Unregister(a.PersistentVolumePriceRecorder)
  294. prometheus.Unregister(a.GPUPriceRecorder)
  295. prometheus.Unregister(a.NodeTotalPriceRecorder)
  296. // zero out the allocation gauges since we want to reset them based on the kubernetes API
  297. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  298. Name: "container_memory_allocation_bytes",
  299. Help: "container_memory_allocation_bytes Bytes of RAM used",
  300. }, []string{"namespace", "pod", "container", "instance", "node"})
  301. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  302. Name: "container_cpu_allocation",
  303. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  304. }, []string{"namespace", "pod", "container", "instance", "node"})
  305. GPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  306. Name: "container_gpu_allocation",
  307. Help: "container_gpu_allocation GPU used",
  308. }, []string{"namespace", "pod", "container", "instance", "node"})
  309. ContainerUptime := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  310. Name: "container_uptime_seconds",
  311. Help: "container_uptime_seconds Seconds a container has been running",
  312. }, []string{"namespace", "pod", "container"})
  313. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  314. Name: "node_cpu_hourly_cost",
  315. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  316. }, []string{"instance", "node"})
  317. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  318. Name: "node_ram_hourly_cost",
  319. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  320. }, []string{"instance", "node"})
  321. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  322. Name: "node_gpu_hourly_cost",
  323. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  324. }, []string{"instance", "node"})
  325. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  326. Name: "node_total_hourly_cost",
  327. Help: "node_total_hourly_cost Total node cost per hour",
  328. }, []string{"instance", "node"})
  329. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  330. Name: "pv_hourly_cost",
  331. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  332. }, []string{"volumename", "persistentvolume"})
  333. prometheus.MustRegister(RAMAllocation)
  334. prometheus.MustRegister(CPUAllocation)
  335. prometheus.MustRegister(GPUAllocation)
  336. prometheus.MustRegister(ContainerUptime)
  337. prometheus.MustRegister(cpuGv)
  338. prometheus.MustRegister(ramGv)
  339. prometheus.MustRegister(gpuGv)
  340. prometheus.MustRegister(totalGv)
  341. prometheus.MustRegister(pvGv)
  342. a.RAMAllocationRecorder = RAMAllocation
  343. a.CPUAllocationRecorder = CPUAllocation
  344. a.GPUAllocationRecorder = GPUAllocation
  345. a.ContainerUptimeRecorder = ContainerUptime
  346. a.CPUPriceRecorder = cpuGv
  347. a.RAMPriceRecorder = ramGv
  348. a.PersistentVolumePriceRecorder = pvGv
  349. a.GPUPriceRecorder = gpuGv
  350. a.NodeTotalPriceRecorder = totalGv
  351. for _, costs := range data {
  352. nodeName := costs.NodeName
  353. node := costs.NodeData
  354. if node == nil {
  355. klog.V(4).Infof("Skipping Node \"%s\" due to missing Node Data costs", nodeName)
  356. continue
  357. }
  358. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  359. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  360. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  361. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  362. gpu, _ := strconv.ParseFloat(node.GPU, 64)
  363. gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64)
  364. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost
  365. if costs.PVCData != nil {
  366. for _, pvc := range costs.PVCData {
  367. pvCost, _ := strconv.ParseFloat(pvc.Volume.Cost, 64)
  368. a.PersistentVolumePriceRecorder.WithLabelValues(pvc.VolumeName, pvc.VolumeName).Set(pvCost)
  369. }
  370. }
  371. a.CPUPriceRecorder.WithLabelValues(nodeName, nodeName).Set(cpuCost)
  372. a.RAMPriceRecorder.WithLabelValues(nodeName, nodeName).Set(ramCost)
  373. a.GPUPriceRecorder.WithLabelValues(nodeName, nodeName).Set(gpuCost)
  374. a.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName).Set(totalCost)
  375. namespace := costs.Namespace
  376. podName := costs.PodName
  377. containerName := costs.Name
  378. if len(costs.RAMAllocation) > 0 {
  379. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.RAMAllocation[0].Value)
  380. }
  381. if len(costs.CPUAllocation) > 0 {
  382. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.CPUAllocation[0].Value)
  383. }
  384. if len(costs.GPUReq) > 0 {
  385. // allocation here is set to the request because shared GPU usage not yet supported.
  386. a.GPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.GPUReq[0].Value)
  387. }
  388. storageClasses, _ := a.KubeClientSet.StorageV1().StorageClasses().List(metav1.ListOptions{})
  389. storageClassMap := make(map[string]map[string]string)
  390. for _, storageClass := range storageClasses.Items {
  391. params := storageClass.Parameters
  392. storageClassMap[storageClass.ObjectMeta.Name] = params
  393. }
  394. pvs, _ := a.KubeClientSet.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  395. for _, pv := range pvs.Items {
  396. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  397. if !ok {
  398. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  399. }
  400. cacPv := &costAnalyzerCloud.PV{
  401. Class: pv.Spec.StorageClassName,
  402. Region: pv.Labels[v1.LabelZoneRegion],
  403. Parameters: parameters,
  404. }
  405. costModel.GetPVCost(cacPv, &pv, a.Cloud)
  406. c, _ := strconv.ParseFloat(cacPv.Cost, 64)
  407. a.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name).Set(c)
  408. }
  409. containerUptime, _ := costModel.ComputeUptimes(a.PrometheusClient)
  410. for key, uptime := range containerUptime {
  411. container, _ := costModel.NewContainerMetricFromKey(key)
  412. a.ContainerUptimeRecorder.WithLabelValues(container.Namespace, container.PodName, container.ContainerName).Set(uptime)
  413. }
  414. }
  415. time.Sleep(time.Minute)
  416. }
  417. }()
  418. }
  419. func main() {
  420. klog.InitFlags(nil)
  421. flag.Set("v", "3")
  422. flag.Parse()
  423. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  424. address := os.Getenv(prometheusServerEndpointEnvVar)
  425. if address == "" {
  426. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  427. }
  428. var LongTimeoutRoundTripper http.RoundTripper = &http.Transport{ // may be necessary for long prometheus queries. TODO: make this configurable
  429. Proxy: http.ProxyFromEnvironment,
  430. DialContext: (&net.Dialer{
  431. Timeout: 120 * time.Second,
  432. KeepAlive: 120 * time.Second,
  433. }).DialContext,
  434. TLSHandshakeTimeout: 10 * time.Second,
  435. }
  436. pc := prometheusClient.Config{
  437. Address: address,
  438. RoundTripper: LongTimeoutRoundTripper,
  439. }
  440. promCli, _ := prometheusClient.NewClient(pc)
  441. api := prometheusAPI.NewAPI(promCli)
  442. _, err := api.Config(context.Background())
  443. if err != nil {
  444. klog.Fatalf("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  445. }
  446. klog.V(1).Info("Success: retrieved a prometheus config file from: " + address)
  447. _, err = costModel.ValidatePrometheus(promCli)
  448. if err != nil {
  449. klog.Fatalf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  450. }
  451. klog.V(1).Info("Success: retrieved the 'up' query against prometheus at: " + address)
  452. // Kubernetes API setup
  453. kc, err := rest.InClusterConfig()
  454. if err != nil {
  455. panic(err.Error())
  456. }
  457. kubeClientset, err := kubernetes.NewForConfig(kc)
  458. if err != nil {
  459. panic(err.Error())
  460. }
  461. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  462. cloudProvider, err := costAnalyzerCloud.NewProvider(kubeClientset, cloudProviderKey)
  463. if err != nil {
  464. panic(err.Error())
  465. }
  466. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  467. Name: "node_cpu_hourly_cost",
  468. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  469. }, []string{"instance", "node"})
  470. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  471. Name: "node_ram_hourly_cost",
  472. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  473. }, []string{"instance", "node"})
  474. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  475. Name: "node_gpu_hourly_cost",
  476. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  477. }, []string{"instance", "node"})
  478. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  479. Name: "node_total_hourly_cost",
  480. Help: "node_total_hourly_cost Total node cost per hour",
  481. }, []string{"instance", "node"})
  482. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  483. Name: "pv_hourly_cost",
  484. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  485. }, []string{"volumename", "persistentvolume"})
  486. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  487. Name: "container_memory_allocation_bytes",
  488. Help: "container_memory_allocation_bytes Bytes of RAM used",
  489. }, []string{"namespace", "pod", "container", "instance", "node"})
  490. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  491. Name: "container_cpu_allocation",
  492. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  493. }, []string{"namespace", "pod", "container", "instance", "node"})
  494. GPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  495. Name: "container_gpu_allocation",
  496. Help: "container_gpu_allocation GPU used",
  497. }, []string{"namespace", "pod", "container", "instance", "node"})
  498. ContainerUptimeRecorder := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  499. Name: "container_uptime_seconds",
  500. Help: "container_uptime_seconds Seconds a container has been running",
  501. }, []string{"namespace", "pod", "container"})
  502. prometheus.MustRegister(cpuGv)
  503. prometheus.MustRegister(ramGv)
  504. prometheus.MustRegister(gpuGv)
  505. prometheus.MustRegister(totalGv)
  506. prometheus.MustRegister(pvGv)
  507. prometheus.MustRegister(RAMAllocation)
  508. prometheus.MustRegister(CPUAllocation)
  509. prometheus.MustRegister(ContainerUptimeRecorder)
  510. a := Accesses{
  511. PrometheusClient: promCli,
  512. KubeClientSet: kubeClientset,
  513. Cloud: cloudProvider,
  514. CPUPriceRecorder: cpuGv,
  515. RAMPriceRecorder: ramGv,
  516. GPUPriceRecorder: gpuGv,
  517. NodeTotalPriceRecorder: totalGv,
  518. RAMAllocationRecorder: RAMAllocation,
  519. CPUAllocationRecorder: CPUAllocation,
  520. GPUAllocationRecorder: GPUAllocation,
  521. ContainerUptimeRecorder: ContainerUptimeRecorder,
  522. PersistentVolumePriceRecorder: pvGv,
  523. Model: costModel.NewCostModel(kubeClientset),
  524. }
  525. err = a.Cloud.DownloadPricingData()
  526. if err != nil {
  527. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  528. }
  529. a.recordPrices()
  530. router := httprouter.New()
  531. router.GET("/costDataModel", a.CostDataModel)
  532. router.GET("/costDataModelRange", a.CostDataModelRange)
  533. router.GET("/outOfClusterCosts", a.OutofClusterCosts)
  534. router.GET("/allNodePricing", a.GetAllNodePricing)
  535. router.GET("/healthz", Healthz)
  536. router.GET("/getConfigs", a.GetConfigs)
  537. router.POST("/refreshPricing", a.RefreshPricingData)
  538. router.POST("/updateSpotInfoConfigs", a.UpdateSpotInfoConfigs)
  539. router.POST("/updateAthenaInfoConfigs", a.UpdateAthenaInfoConfigs)
  540. router.POST("/updateBigQueryInfoConfigs", a.UpdateBigQueryInfoConfigs)
  541. router.POST("/updateConfigByKey", a.UpdateConfigByKey)
  542. router.GET("/clusterCostsOverTime", a.ClusterCostsOverTime)
  543. router.GET("/clusterCosts", a.ClusterCosts)
  544. router.GET("/validatePrometheus", a.GetPrometheusMetadata)
  545. router.GET("/managementPlatform", a.ManagementPlatform)
  546. router.GET("/clusterInfo", a.ClusterInfo)
  547. router.GET("/containerUptimes", a.ContainerUptimes)
  548. rootMux := http.NewServeMux()
  549. rootMux.Handle("/", router)
  550. rootMux.Handle("/metrics", promhttp.Handler())
  551. klog.Fatal(http.ListenAndServe(":9003", rootMux))
  552. }