metrics.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. package prometheus
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. v1 "k8s.io/api/core/v1"
  8. "k8s.io/client-go/kubernetes"
  9. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  10. )
  11. // returns the prometheus service name
  12. func GetPrometheusService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
  13. services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
  14. LabelSelector: "app=prometheus,component=server,heritage=Helm",
  15. })
  16. if err != nil {
  17. return nil, false, err
  18. }
  19. if len(services.Items) == 0 {
  20. return nil, false, nil
  21. }
  22. return &services.Items[0], true, nil
  23. }
  24. // returns the prometheus service name
  25. func getKubeStateMetricsService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
  26. services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
  27. LabelSelector: "app.kubernetes.io/name=kube-state-metrics",
  28. })
  29. if err != nil {
  30. return nil, false, err
  31. }
  32. if len(services.Items) == 0 {
  33. return nil, false, nil
  34. }
  35. return &services.Items[0], true, nil
  36. }
  37. type SimpleIngress struct {
  38. Name string `json:"name"`
  39. Namespace string `json:"namespace"`
  40. }
  41. // GetIngressesWithNGINXAnnotation gets an array of names for all ingresses controlled by
  42. // NGINX
  43. func GetIngressesWithNGINXAnnotation(clientset kubernetes.Interface) ([]SimpleIngress, error) {
  44. res := make([]SimpleIngress, 0)
  45. foundMap := make(map[string]bool)
  46. v1beta1IngressList, v1beta1Err := clientset.NetworkingV1beta1().Ingresses("").List(context.TODO(), metav1.ListOptions{})
  47. v1IngressList, v1Err := clientset.NetworkingV1().Ingresses("").List(context.TODO(), metav1.ListOptions{})
  48. if v1beta1Err != nil && v1Err != nil {
  49. return nil, fmt.Errorf("List ingresses error: %s, %s", v1beta1Err.Error(), v1Err.Error())
  50. }
  51. if v1beta1Err == nil && len(v1beta1IngressList.Items) > 0 {
  52. for _, ingress := range v1beta1IngressList.Items {
  53. ingressAnn, found := ingress.ObjectMeta.Annotations["kubernetes.io/ingress.class"]
  54. uid := fmt.Sprintf("%s/%s", ingress.ObjectMeta.Namespace, ingress.ObjectMeta.Name)
  55. if _, exists := foundMap[uid]; !exists && ((found && ingressAnn == "nginx") || *ingress.Spec.IngressClassName == "nginx") {
  56. res = append(res, SimpleIngress{
  57. Name: ingress.ObjectMeta.Name,
  58. Namespace: ingress.ObjectMeta.Namespace,
  59. })
  60. foundMap[uid] = true
  61. }
  62. }
  63. }
  64. if v1Err == nil && len(v1IngressList.Items) > 0 {
  65. for _, ingress := range v1IngressList.Items {
  66. ingressAnn, found := ingress.ObjectMeta.Annotations["kubernetes.io/ingress.class"]
  67. uid := fmt.Sprintf("%s/%s", ingress.ObjectMeta.Namespace, ingress.ObjectMeta.Name)
  68. if _, exists := foundMap[uid]; !exists && ((found && ingressAnn == "nginx") || *ingress.Spec.IngressClassName == "nginx") {
  69. res = append(res, SimpleIngress{
  70. Name: ingress.ObjectMeta.Name,
  71. Namespace: ingress.ObjectMeta.Namespace,
  72. })
  73. foundMap[uid] = true
  74. }
  75. }
  76. }
  77. return res, nil
  78. }
  79. type QueryOpts struct {
  80. Metric string `schema:"metric"`
  81. ShouldSum bool `schema:"shouldsum"`
  82. Kind string `schema:"kind"`
  83. PodList []string `schema:"pods"`
  84. Name string `schema:"name"`
  85. Namespace string `schema:"namespace"`
  86. StartRange uint `schema:"startrange"`
  87. EndRange uint `schema:"endrange"`
  88. Resolution string `schema:"resolution"`
  89. Percentile float64 `schema:"percentile"`
  90. }
  91. func QueryPrometheus(
  92. clientset kubernetes.Interface,
  93. service *v1.Service,
  94. opts *QueryOpts,
  95. ) ([]*promParsedSingletonQuery, error) {
  96. if len(service.Spec.Ports) == 0 {
  97. return nil, fmt.Errorf("prometheus service has no exposed ports to query")
  98. }
  99. selectionRegex, err := getSelectionRegex(opts.Kind, opts.Name)
  100. if err != nil {
  101. return nil, err
  102. }
  103. var podSelector string
  104. if len(opts.PodList) > 0 {
  105. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, strings.Join(opts.PodList, "|"))
  106. } else {
  107. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, selectionRegex)
  108. }
  109. query := ""
  110. if opts.Metric == "cpu" {
  111. query = fmt.Sprintf("rate(container_cpu_usage_seconds_total{%s}[5m])", podSelector)
  112. } else if opts.Metric == "memory" {
  113. query = fmt.Sprintf("container_memory_usage_bytes{%s}", podSelector)
  114. } else if opts.Metric == "network" {
  115. netPodSelector := fmt.Sprintf(`namespace="%s",pod=~"%s",container="POD"`, opts.Namespace, selectionRegex)
  116. query = fmt.Sprintf("rate(container_network_receive_bytes_total{%s}[5m])", netPodSelector)
  117. } else if opts.Metric == "nginx:errors" {
  118. num := fmt.Sprintf(`sum(rate(nginx_ingress_controller_requests{status=~"5.*",exported_namespace="%s",ingress=~"%s"}[5m]) OR on() vector(0))`, opts.Namespace, selectionRegex)
  119. denom := fmt.Sprintf(`sum(rate(nginx_ingress_controller_requests{exported_namespace="%s",ingress=~"%s"}[5m]) > 0)`, opts.Namespace, selectionRegex)
  120. query = fmt.Sprintf(`%s / %s * 100 OR on() vector(0)`, num, denom)
  121. } else if opts.Metric == "nginx:latency" {
  122. num := fmt.Sprintf(`sum(rate(nginx_ingress_controller_request_duration_seconds_sum{exported_namespace=~"%s",ingress=~"%s"}[5m]) OR on() vector(0))`, opts.Namespace, selectionRegex)
  123. denom := fmt.Sprintf(`sum(rate(nginx_ingress_controller_request_duration_seconds_count{exported_namespace=~"%s",ingress=~"%s"}[5m]))`, opts.Namespace, selectionRegex)
  124. query = fmt.Sprintf(`%s / %s OR on() vector(0)`, num, denom)
  125. } else if opts.Metric == "nginx:latency-histogram" {
  126. query = fmt.Sprintf(`histogram_quantile(%f, sum(rate(nginx_ingress_controller_request_duration_seconds_bucket{status!="404",status!="500",exported_namespace=~"%s",ingress=~"%s"}[5m])) by (le, ingress))`, opts.Percentile, opts.Namespace, selectionRegex)
  127. } else if opts.Metric == "cpu_hpa_threshold" {
  128. // get the name of the kube hpa metric
  129. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  130. cpuMetricName := getKubeCPUMetricName(clientset, service, opts)
  131. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  132. appLabel := ""
  133. if found {
  134. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  135. }
  136. query = createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  137. } else if opts.Metric == "memory_hpa_threshold" {
  138. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  139. memMetricName := getKubeMemoryMetricName(clientset, service, opts)
  140. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  141. appLabel := ""
  142. if found {
  143. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  144. }
  145. query = createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  146. } else if opts.Metric == "hpa_replicas" {
  147. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "status_current_replicas")
  148. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  149. appLabel := ""
  150. if found {
  151. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  152. }
  153. query = createHPACurrentReplicasQuery(metricName, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  154. }
  155. if opts.ShouldSum {
  156. query = fmt.Sprintf("sum(%s)", query)
  157. }
  158. queryParams := map[string]string{
  159. "query": query,
  160. "start": fmt.Sprintf("%d", opts.StartRange),
  161. "end": fmt.Sprintf("%d", opts.EndRange),
  162. "step": opts.Resolution,
  163. }
  164. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  165. "http",
  166. service.Name,
  167. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  168. "/api/v1/query_range",
  169. queryParams,
  170. )
  171. rawQuery, err := resp.DoRaw(context.TODO())
  172. if err != nil {
  173. return nil, err
  174. }
  175. return parseQuery(rawQuery, opts.Metric)
  176. }
  177. type promRawQuery struct {
  178. Data struct {
  179. Result []struct {
  180. Metric struct {
  181. Pod string `json:"pod,omitempty"`
  182. } `json:"metric,omitempty"`
  183. Values [][]interface{} `json:"values"`
  184. } `json:"result"`
  185. } `json:"data"`
  186. }
  187. type promParsedSingletonQueryResult struct {
  188. Date interface{} `json:"date,omitempty"`
  189. CPU interface{} `json:"cpu,omitempty"`
  190. Replicas interface{} `json:"replicas,omitempty"`
  191. Memory interface{} `json:"memory,omitempty"`
  192. Bytes interface{} `json:"bytes,omitempty"`
  193. ErrorPct interface{} `json:"error_pct,omitempty"`
  194. Latency interface{} `json:"latency,omitempty"`
  195. }
  196. type promParsedSingletonQuery struct {
  197. Pod string `json:"pod,omitempty"`
  198. Results []promParsedSingletonQueryResult `json:"results"`
  199. }
  200. func parseQuery(rawQuery []byte, metric string) ([]*promParsedSingletonQuery, error) {
  201. rawQueryObj := &promRawQuery{}
  202. err := json.Unmarshal(rawQuery, rawQueryObj)
  203. if err != nil {
  204. return nil, err
  205. }
  206. res := make([]*promParsedSingletonQuery, 0)
  207. for _, result := range rawQueryObj.Data.Result {
  208. singleton := &promParsedSingletonQuery{
  209. Pod: result.Metric.Pod,
  210. }
  211. singletonResults := make([]promParsedSingletonQueryResult, 0)
  212. for _, values := range result.Values {
  213. singletonResult := &promParsedSingletonQueryResult{
  214. Date: values[0],
  215. }
  216. if metric == "cpu" {
  217. singletonResult.CPU = values[1]
  218. } else if metric == "memory" {
  219. singletonResult.Memory = values[1]
  220. } else if metric == "network" {
  221. singletonResult.Bytes = values[1]
  222. } else if metric == "nginx:errors" {
  223. singletonResult.ErrorPct = values[1]
  224. } else if metric == "cpu_hpa_threshold" {
  225. singletonResult.CPU = values[1]
  226. } else if metric == "memory_hpa_threshold" {
  227. singletonResult.Memory = values[1]
  228. } else if metric == "hpa_replicas" {
  229. singletonResult.Replicas = values[1]
  230. } else if metric == "nginx:latency" || metric == "nginx:latency-histogram" {
  231. singletonResult.Latency = values[1]
  232. }
  233. singletonResults = append(singletonResults, *singletonResult)
  234. }
  235. singleton.Results = singletonResults
  236. res = append(res, singleton)
  237. }
  238. return res, nil
  239. }
  240. func getSelectionRegex(kind, name string) (string, error) {
  241. var suffix string
  242. switch strings.ToLower(kind) {
  243. case "deployment":
  244. suffix = "[a-z0-9]+(-[a-z0-9]+)*"
  245. case "statefulset":
  246. suffix = "[0-9]+"
  247. case "job":
  248. suffix = "[a-z0-9]+"
  249. case "cronjob":
  250. suffix = "[a-z0-9]+-[a-z0-9]+"
  251. case "ingress":
  252. return name, nil
  253. case "daemonset":
  254. suffix = "[a-z0-9]+"
  255. default:
  256. return "", fmt.Errorf("not a supported controller to query for metrics")
  257. }
  258. return fmt.Sprintf("%s-%s", name, suffix), nil
  259. }
  260. func createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  261. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  262. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  263. kubeMetricsHPASelectorOne := fmt.Sprintf(
  264. `%s="%s",namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  265. hpaMetricName,
  266. hpaName,
  267. namespace,
  268. )
  269. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  270. `%s="%s",exported_namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  271. hpaMetricName,
  272. hpaName,
  273. namespace,
  274. )
  275. if cpuMetricName == "kube_pod_container_resource_requests" {
  276. kubeMetricsPodSelectorOne += `,resource="cpu",unit="core"`
  277. kubeMetricsPodSelectorTwo += `,resource="cpu",unit="core"`
  278. }
  279. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  280. // as well
  281. if appLabel != "" {
  282. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  283. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  284. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  285. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  286. }
  287. requestCPUOne := fmt.Sprintf(
  288. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  289. hpaMetricName,
  290. cpuMetricName,
  291. kubeMetricsPodSelectorOne,
  292. hpaMetricName,
  293. hpaName,
  294. )
  295. targetCPUUtilThresholdOne := fmt.Sprintf(
  296. `%s{%s} / 100`,
  297. metricName,
  298. kubeMetricsHPASelectorOne,
  299. )
  300. requestCPUTwo := fmt.Sprintf(
  301. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  302. hpaMetricName,
  303. cpuMetricName,
  304. kubeMetricsPodSelectorTwo,
  305. hpaMetricName,
  306. hpaName,
  307. )
  308. targetCPUUtilThresholdTwo := fmt.Sprintf(
  309. `%s{%s} / 100`,
  310. metricName,
  311. kubeMetricsHPASelectorTwo,
  312. )
  313. return fmt.Sprintf(
  314. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  315. requestCPUOne, hpaMetricName, targetCPUUtilThresholdOne,
  316. requestCPUTwo, hpaMetricName, targetCPUUtilThresholdTwo,
  317. )
  318. }
  319. func createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  320. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  321. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  322. kubeMetricsHPASelectorOne := fmt.Sprintf(
  323. `%s="%s",namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  324. hpaMetricName,
  325. hpaName,
  326. namespace,
  327. )
  328. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  329. `%s="%s",exported_namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  330. hpaMetricName,
  331. hpaName,
  332. namespace,
  333. )
  334. if memMetricName == "kube_pod_container_resource_requests" {
  335. kubeMetricsPodSelectorOne += `,resource="memory",unit="byte"`
  336. kubeMetricsPodSelectorTwo += `,resource="memory",unit="byte"`
  337. }
  338. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  339. // as well
  340. if appLabel != "" {
  341. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  342. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  343. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  344. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  345. }
  346. requestMemOne := fmt.Sprintf(
  347. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  348. hpaMetricName,
  349. memMetricName,
  350. kubeMetricsPodSelectorOne,
  351. hpaMetricName,
  352. hpaName,
  353. )
  354. targetMemUtilThresholdOne := fmt.Sprintf(
  355. `%s{%s} / 100`,
  356. metricName,
  357. kubeMetricsHPASelectorOne,
  358. )
  359. requestMemTwo := fmt.Sprintf(
  360. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  361. hpaMetricName,
  362. memMetricName,
  363. kubeMetricsPodSelectorTwo,
  364. hpaMetricName,
  365. hpaName,
  366. )
  367. targetMemUtilThresholdTwo := fmt.Sprintf(
  368. `%s{%s} / 100`,
  369. metricName,
  370. kubeMetricsHPASelectorTwo,
  371. )
  372. return fmt.Sprintf(
  373. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  374. requestMemOne, hpaMetricName, targetMemUtilThresholdOne,
  375. requestMemTwo, hpaMetricName, targetMemUtilThresholdTwo,
  376. )
  377. }
  378. func getKubeMetricsPodSelector(podSelectionRegex, namespace, namespaceLabel string) string {
  379. return fmt.Sprintf(
  380. `pod=~"%s",%s="%s",container!="POD",container!=""`,
  381. podSelectionRegex,
  382. namespaceLabel,
  383. namespace,
  384. )
  385. }
  386. func createHPACurrentReplicasQuery(metricName, hpaName, namespace, appLabel, hpaMetricName string) string {
  387. kubeMetricsHPASelectorOne := fmt.Sprintf(
  388. `%s="%s",namespace="%s"`,
  389. hpaMetricName,
  390. hpaName,
  391. namespace,
  392. )
  393. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  394. `%s="%s",exported_namespace="%s"`,
  395. hpaMetricName,
  396. hpaName,
  397. namespace,
  398. )
  399. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  400. // as well
  401. if appLabel != "" {
  402. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  403. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  404. }
  405. return fmt.Sprintf(
  406. `(%s{%s}) or (%s{%s})`,
  407. metricName,
  408. kubeMetricsHPASelectorOne,
  409. metricName,
  410. kubeMetricsHPASelectorTwo,
  411. )
  412. }
  413. type promRawValuesQuery struct {
  414. Status string `json:"status"`
  415. Data []string `json:"data"`
  416. }
  417. // getKubeHPAMetricName performs a "best guess" for the name of the kube HPA metric,
  418. // which was renamed to kube_horizontalpodautoscaler... in later versions of kube-state-metrics.
  419. // we query Prometheus for a list of metric names to see if any match the new query
  420. // value, otherwise we return the deprecated name.
  421. func getKubeHPAMetricName(
  422. clientset kubernetes.Interface,
  423. service *v1.Service,
  424. opts *QueryOpts,
  425. suffix string,
  426. ) (string, string) {
  427. queryParams := map[string]string{
  428. "match[]": fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix),
  429. "start": fmt.Sprintf("%d", opts.StartRange),
  430. "end": fmt.Sprintf("%d", opts.EndRange),
  431. }
  432. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  433. "http",
  434. service.Name,
  435. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  436. "/api/v1/label/__name__/values",
  437. queryParams,
  438. )
  439. rawQuery, err := resp.DoRaw(context.TODO())
  440. if err != nil {
  441. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  442. }
  443. rawQueryObj := &promRawValuesQuery{}
  444. json.Unmarshal(rawQuery, rawQueryObj)
  445. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  446. return fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix), "horizontalpodautoscaler"
  447. }
  448. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  449. }
  450. func getKubeCPUMetricName(
  451. clientset kubernetes.Interface,
  452. service *v1.Service,
  453. opts *QueryOpts,
  454. ) string {
  455. queryParams := map[string]string{
  456. "match[]": "kube_pod_container_resource_requests",
  457. "start": fmt.Sprintf("%d", opts.StartRange),
  458. "end": fmt.Sprintf("%d", opts.EndRange),
  459. }
  460. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  461. "http",
  462. service.Name,
  463. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  464. "/api/v1/label/__name__/values",
  465. queryParams,
  466. )
  467. rawQuery, err := resp.DoRaw(context.TODO())
  468. if err != nil {
  469. return "kube_pod_container_resource_requests_cpu_cores"
  470. }
  471. rawQueryObj := &promRawValuesQuery{}
  472. json.Unmarshal(rawQuery, rawQueryObj)
  473. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  474. return "kube_pod_container_resource_requests"
  475. }
  476. return "kube_pod_container_resource_requests_cpu_cores"
  477. }
  478. func getKubeMemoryMetricName(
  479. clientset kubernetes.Interface,
  480. service *v1.Service,
  481. opts *QueryOpts,
  482. ) string {
  483. queryParams := map[string]string{
  484. "match[]": "kube_pod_container_resource_requests",
  485. "start": fmt.Sprintf("%d", opts.StartRange),
  486. "end": fmt.Sprintf("%d", opts.EndRange),
  487. }
  488. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  489. "http",
  490. service.Name,
  491. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  492. "/api/v1/label/__name__/values",
  493. queryParams,
  494. )
  495. rawQuery, err := resp.DoRaw(context.TODO())
  496. if err != nil {
  497. return "kube_pod_container_resource_requests_memory_bytes"
  498. }
  499. rawQueryObj := &promRawValuesQuery{}
  500. json.Unmarshal(rawQuery, rawQueryObj)
  501. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  502. return "kube_pod_container_resource_requests"
  503. }
  504. return "kube_pod_container_resource_requests_memory_bytes"
  505. }