2
0

metrics.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. default:
  254. return "", fmt.Errorf("not a supported controller to query for metrics")
  255. }
  256. return fmt.Sprintf("%s-%s", name, suffix), nil
  257. }
  258. func createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  259. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  260. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  261. kubeMetricsHPASelectorOne := fmt.Sprintf(
  262. `%s="%s",namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  263. hpaMetricName,
  264. hpaName,
  265. namespace,
  266. )
  267. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  268. `%s="%s",exported_namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  269. hpaMetricName,
  270. hpaName,
  271. namespace,
  272. )
  273. if cpuMetricName == "kube_pod_container_resource_requests" {
  274. kubeMetricsPodSelectorOne += `,resource="cpu",unit="core"`
  275. kubeMetricsPodSelectorTwo += `,resource="cpu",unit="core"`
  276. }
  277. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  278. // as well
  279. if appLabel != "" {
  280. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  281. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  282. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  283. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  284. }
  285. requestCPUOne := fmt.Sprintf(
  286. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  287. hpaMetricName,
  288. cpuMetricName,
  289. kubeMetricsPodSelectorOne,
  290. hpaMetricName,
  291. hpaName,
  292. )
  293. targetCPUUtilThresholdOne := fmt.Sprintf(
  294. `%s{%s} / 100`,
  295. metricName,
  296. kubeMetricsHPASelectorOne,
  297. )
  298. requestCPUTwo := fmt.Sprintf(
  299. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  300. hpaMetricName,
  301. cpuMetricName,
  302. kubeMetricsPodSelectorTwo,
  303. hpaMetricName,
  304. hpaName,
  305. )
  306. targetCPUUtilThresholdTwo := fmt.Sprintf(
  307. `%s{%s} / 100`,
  308. metricName,
  309. kubeMetricsHPASelectorTwo,
  310. )
  311. return fmt.Sprintf(
  312. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  313. requestCPUOne, hpaMetricName, targetCPUUtilThresholdOne,
  314. requestCPUTwo, hpaMetricName, targetCPUUtilThresholdTwo,
  315. )
  316. }
  317. func createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  318. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  319. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  320. kubeMetricsHPASelectorOne := fmt.Sprintf(
  321. `%s="%s",namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  322. hpaMetricName,
  323. hpaName,
  324. namespace,
  325. )
  326. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  327. `%s="%s",exported_namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  328. hpaMetricName,
  329. hpaName,
  330. namespace,
  331. )
  332. if memMetricName == "kube_pod_container_resource_requests" {
  333. kubeMetricsPodSelectorOne += `,resource="memory",unit="byte"`
  334. kubeMetricsPodSelectorTwo += `,resource="memory",unit="byte"`
  335. }
  336. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  337. // as well
  338. if appLabel != "" {
  339. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  340. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  341. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  342. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  343. }
  344. requestMemOne := fmt.Sprintf(
  345. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  346. hpaMetricName,
  347. memMetricName,
  348. kubeMetricsPodSelectorOne,
  349. hpaMetricName,
  350. hpaName,
  351. )
  352. targetMemUtilThresholdOne := fmt.Sprintf(
  353. `%s{%s} / 100`,
  354. metricName,
  355. kubeMetricsHPASelectorOne,
  356. )
  357. requestMemTwo := fmt.Sprintf(
  358. `sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  359. hpaMetricName,
  360. memMetricName,
  361. kubeMetricsPodSelectorTwo,
  362. hpaMetricName,
  363. hpaName,
  364. )
  365. targetMemUtilThresholdTwo := fmt.Sprintf(
  366. `%s{%s} / 100`,
  367. metricName,
  368. kubeMetricsHPASelectorTwo,
  369. )
  370. return fmt.Sprintf(
  371. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  372. requestMemOne, hpaMetricName, targetMemUtilThresholdOne,
  373. requestMemTwo, hpaMetricName, targetMemUtilThresholdTwo,
  374. )
  375. }
  376. func getKubeMetricsPodSelector(podSelectionRegex, namespace, namespaceLabel string) string {
  377. return fmt.Sprintf(
  378. `pod=~"%s",%s="%s",container!="POD",container!=""`,
  379. podSelectionRegex,
  380. namespaceLabel,
  381. namespace,
  382. )
  383. }
  384. func createHPACurrentReplicasQuery(metricName, hpaName, namespace, appLabel, hpaMetricName string) string {
  385. kubeMetricsHPASelectorOne := fmt.Sprintf(
  386. `%s="%s",namespace="%s"`,
  387. hpaMetricName,
  388. hpaName,
  389. namespace,
  390. )
  391. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  392. `%s="%s",exported_namespace="%s"`,
  393. hpaMetricName,
  394. hpaName,
  395. namespace,
  396. )
  397. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  398. // as well
  399. if appLabel != "" {
  400. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  401. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  402. }
  403. return fmt.Sprintf(
  404. `(%s{%s}) or (%s{%s})`,
  405. metricName,
  406. kubeMetricsHPASelectorOne,
  407. metricName,
  408. kubeMetricsHPASelectorTwo,
  409. )
  410. }
  411. type promRawValuesQuery struct {
  412. Status string `json:"status"`
  413. Data []string `json:"data"`
  414. }
  415. // getKubeHPAMetricName performs a "best guess" for the name of the kube HPA metric,
  416. // which was renamed to kube_horizontalpodautoscaler... in later versions of kube-state-metrics.
  417. // we query Prometheus for a list of metric names to see if any match the new query
  418. // value, otherwise we return the deprecated name.
  419. func getKubeHPAMetricName(
  420. clientset kubernetes.Interface,
  421. service *v1.Service,
  422. opts *QueryOpts,
  423. suffix string,
  424. ) (string, string) {
  425. queryParams := map[string]string{
  426. "match[]": fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix),
  427. "start": fmt.Sprintf("%d", opts.StartRange),
  428. "end": fmt.Sprintf("%d", opts.EndRange),
  429. }
  430. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  431. "http",
  432. service.Name,
  433. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  434. "/api/v1/label/__name__/values",
  435. queryParams,
  436. )
  437. rawQuery, err := resp.DoRaw(context.TODO())
  438. if err != nil {
  439. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  440. }
  441. rawQueryObj := &promRawValuesQuery{}
  442. json.Unmarshal(rawQuery, rawQueryObj)
  443. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  444. return fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix), "horizontalpodautoscaler"
  445. }
  446. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  447. }
  448. func getKubeCPUMetricName(
  449. clientset kubernetes.Interface,
  450. service *v1.Service,
  451. opts *QueryOpts,
  452. ) string {
  453. queryParams := map[string]string{
  454. "match[]": "kube_pod_container_resource_requests",
  455. "start": fmt.Sprintf("%d", opts.StartRange),
  456. "end": fmt.Sprintf("%d", opts.EndRange),
  457. }
  458. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  459. "http",
  460. service.Name,
  461. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  462. "/api/v1/label/__name__/values",
  463. queryParams,
  464. )
  465. rawQuery, err := resp.DoRaw(context.TODO())
  466. if err != nil {
  467. return "kube_pod_container_resource_requests_cpu_cores"
  468. }
  469. rawQueryObj := &promRawValuesQuery{}
  470. json.Unmarshal(rawQuery, rawQueryObj)
  471. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  472. return "kube_pod_container_resource_requests"
  473. }
  474. return "kube_pod_container_resource_requests_cpu_cores"
  475. }
  476. func getKubeMemoryMetricName(
  477. clientset kubernetes.Interface,
  478. service *v1.Service,
  479. opts *QueryOpts,
  480. ) string {
  481. queryParams := map[string]string{
  482. "match[]": "kube_pod_container_resource_requests",
  483. "start": fmt.Sprintf("%d", opts.StartRange),
  484. "end": fmt.Sprintf("%d", opts.EndRange),
  485. }
  486. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  487. "http",
  488. service.Name,
  489. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  490. "/api/v1/label/__name__/values",
  491. queryParams,
  492. )
  493. rawQuery, err := resp.DoRaw(context.TODO())
  494. if err != nil {
  495. return "kube_pod_container_resource_requests_memory_bytes"
  496. }
  497. rawQueryObj := &promRawValuesQuery{}
  498. json.Unmarshal(rawQuery, rawQueryObj)
  499. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  500. return "kube_pod_container_resource_requests"
  501. }
  502. return "kube_pod_container_resource_requests_memory_bytes"
  503. }