metrics.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. package prometheus
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "github.com/porter-dev/porter/internal/telemetry"
  10. v1 "k8s.io/api/core/v1"
  11. "k8s.io/client-go/kubernetes"
  12. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  13. )
  14. type ListNGINXIngressesResponse []SimpleIngress
  15. type GetPodMetricsRequest struct {
  16. QueryOpts
  17. }
  18. // GetPrometheusService returns the prometheus service name. The prometheus-community/prometheus chart @ v15.5.3 uses non-FQDN labels, unlike v22.6.2. This function checks for both labels.
  19. func GetPrometheusService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
  20. redundantServices, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
  21. LabelSelector: "app=prometheus,component=server,heritage=Helm",
  22. })
  23. if err != nil {
  24. return nil, false, err
  25. }
  26. upgradedServices, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
  27. LabelSelector: "app.kubernetes.io/component=server,app.kubernetes.io/instance=prometheus,app.kubernetes.io/managed-by=Helm",
  28. })
  29. if err != nil {
  30. return nil, false, err
  31. }
  32. if len(redundantServices.Items) > 0 {
  33. return &redundantServices.Items[0], true, nil
  34. }
  35. if len(upgradedServices.Items) > 0 {
  36. return &upgradedServices.Items[0], true, nil
  37. }
  38. return nil, false, err
  39. }
  40. // getKubeStateMetricsService returns the prometheus service name
  41. func getKubeStateMetricsService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
  42. services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
  43. LabelSelector: "app.kubernetes.io/name=kube-state-metrics",
  44. })
  45. if err != nil {
  46. return nil, false, err
  47. }
  48. if len(services.Items) == 0 {
  49. return nil, false, nil
  50. }
  51. return &services.Items[0], true, nil
  52. }
  53. type SimpleIngress struct {
  54. Name string `json:"name"`
  55. Namespace string `json:"namespace"`
  56. }
  57. // GetIngressesWithNGINXAnnotation gets an array of names for all ingresses controlled by
  58. // NGINX
  59. func GetIngressesWithNGINXAnnotation(clientset kubernetes.Interface) ([]SimpleIngress, error) {
  60. res := make([]SimpleIngress, 0)
  61. foundMap := make(map[string]bool)
  62. v1beta1IngressList, v1beta1Err := clientset.NetworkingV1beta1().Ingresses("").List(context.TODO(), metav1.ListOptions{})
  63. v1IngressList, v1Err := clientset.NetworkingV1().Ingresses("").List(context.TODO(), metav1.ListOptions{})
  64. if v1beta1Err != nil && v1Err != nil {
  65. return nil, fmt.Errorf("List ingresses error: %s, %s", v1beta1Err.Error(), v1Err.Error())
  66. }
  67. if v1beta1Err == nil && len(v1beta1IngressList.Items) > 0 {
  68. for _, ingress := range v1beta1IngressList.Items {
  69. ingressAnn, found := ingress.ObjectMeta.Annotations["kubernetes.io/ingress.class"]
  70. uid := fmt.Sprintf("%s/%s", ingress.ObjectMeta.Namespace, ingress.ObjectMeta.Name)
  71. if _, exists := foundMap[uid]; !exists && ((found && ingressAnn == "nginx") || *ingress.Spec.IngressClassName == "nginx") {
  72. res = append(res, SimpleIngress{
  73. Name: ingress.ObjectMeta.Name,
  74. Namespace: ingress.ObjectMeta.Namespace,
  75. })
  76. foundMap[uid] = true
  77. }
  78. }
  79. }
  80. if v1Err == nil && len(v1IngressList.Items) > 0 {
  81. for _, ingress := range v1IngressList.Items {
  82. ingressAnn, found := ingress.ObjectMeta.Annotations["kubernetes.io/ingress.class"]
  83. uid := fmt.Sprintf("%s/%s", ingress.ObjectMeta.Namespace, ingress.ObjectMeta.Name)
  84. if _, exists := foundMap[uid]; !exists && ((found && ingressAnn == "nginx") || *ingress.Spec.IngressClassName == "nginx") {
  85. res = append(res, SimpleIngress{
  86. Name: ingress.ObjectMeta.Name,
  87. Namespace: ingress.ObjectMeta.Namespace,
  88. })
  89. foundMap[uid] = true
  90. }
  91. }
  92. }
  93. return res, nil
  94. }
  95. type QueryOpts struct {
  96. // the name of the metric being queried for
  97. Metric string `schema:"metric"`
  98. ShouldSum bool `schema:"shouldsum"`
  99. Kind string `schema:"kind"`
  100. PodList []string `schema:"pods"`
  101. Name string `schema:"name"`
  102. Namespace string `schema:"namespace"`
  103. // start time (in unix timestamp) for prometheus results
  104. StartRange uint `schema:"startrange"`
  105. // end time time (in unix timestamp) for prometheus results
  106. EndRange uint `schema:"endrange"`
  107. Resolution string `schema:"resolution"`
  108. Percentile float64 `schema:"percentile"`
  109. }
  110. func QueryPrometheus(
  111. ctx context.Context,
  112. clientset kubernetes.Interface,
  113. service *v1.Service,
  114. opts *QueryOpts,
  115. ) ([]*promParsedSingletonQuery, error) {
  116. ctx, span := telemetry.NewSpan(ctx, "query-prometheus")
  117. defer span.End()
  118. telemetry.WithAttributes(span,
  119. telemetry.AttributeKV{Key: "metric", Value: opts.Metric},
  120. telemetry.AttributeKV{Key: "should-sum", Value: opts.ShouldSum},
  121. telemetry.AttributeKV{Key: "kind", Value: opts.Kind},
  122. telemetry.AttributeKV{Key: "pod-list", Value: strings.Join(opts.PodList, ",")},
  123. telemetry.AttributeKV{Key: "name", Value: opts.Name},
  124. telemetry.AttributeKV{Key: "namespace", Value: opts.Namespace},
  125. telemetry.AttributeKV{Key: "start-range", Value: opts.StartRange},
  126. telemetry.AttributeKV{Key: "end-range", Value: opts.EndRange},
  127. telemetry.AttributeKV{Key: "resolution", Value: opts.Resolution},
  128. telemetry.AttributeKV{Key: "percentile", Value: opts.Percentile},
  129. )
  130. if len(service.Spec.Ports) == 0 {
  131. return nil, telemetry.Error(ctx, span, nil, "prometheus service has no exposed ports to query")
  132. }
  133. selectionRegex, err := getSelectionRegex(opts.Kind, opts.Name)
  134. if err != nil {
  135. return nil, telemetry.Error(ctx, span, err, "failed to get selection regex")
  136. }
  137. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "selection-regex", Value: selectionRegex})
  138. var podSelector string
  139. if len(opts.PodList) > 0 {
  140. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, strings.Join(opts.PodList, "|"))
  141. } else {
  142. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, selectionRegex)
  143. }
  144. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "pod-selector", Value: podSelector})
  145. query := ""
  146. if opts.Metric == "cpu" {
  147. query = fmt.Sprintf("rate(container_cpu_usage_seconds_total{%s}[5m])", podSelector)
  148. } else if opts.Metric == "memory" {
  149. query = fmt.Sprintf("container_memory_usage_bytes{%s}", podSelector)
  150. } else if opts.Metric == "network" {
  151. netPodSelector := fmt.Sprintf(`namespace="%s",pod=~"%s"`, opts.Namespace, selectionRegex)
  152. query = fmt.Sprintf("rate(container_network_receive_bytes_total{%s}[5m])", netPodSelector)
  153. } else if opts.Metric == "nginx:errors" {
  154. num := fmt.Sprintf(`(sum(rate(nginx_ingress_controller_requests{status=~"5.*",exported_namespace="%s",ingress=~"%s"}[5m]) OR sum(rate(nginx_ingress_controller_requests{status=~"5.*",namespace="%s",ingress=~"%s"}[5m])) OR on() vector(0))`, opts.Namespace, selectionRegex, opts.Namespace, selectionRegex)
  155. denom := fmt.Sprintf(`(sum(rate(nginx_ingress_controller_requests{exported_namespace="%s",ingress=~"%s"}[5m]) OR sum(rate(nginx_ingress_controller_requests{namespace="%s",ingress=~"%s"}[5m])) > 0)`, opts.Namespace, selectionRegex, opts.Namespace, selectionRegex)
  156. query = fmt.Sprintf(`%s / %s * 100 OR on() vector(0)`, num, denom)
  157. } else if opts.Metric == "nginx:latency" {
  158. num := fmt.Sprintf(`(sum(rate(nginx_ingress_controller_request_duration_seconds_sum{exported_namespace=~"%s",ingress=~"%s"}[5m]) OR sum(rate(nginx_ingress_controller_request_duration_seconds_sum{namespace=~"%s",ingress=~"%s"}[5m])) OR on() vector(0))`, opts.Namespace, selectionRegex, opts.Namespace, selectionRegex)
  159. denom := fmt.Sprintf(`(sum(rate(nginx_ingress_controller_request_duration_seconds_count{exported_namespace=~"%s",ingress=~"%s"}[5m])) OR sum(rate(nginx_ingress_controller_request_duration_seconds_count{namespace=~"%s",ingress=~"%s"}[5m])))`, opts.Namespace, selectionRegex, opts.Namespace, selectionRegex)
  160. query = fmt.Sprintf(`%s / %s OR on() vector(0)`, num, denom)
  161. } else if opts.Metric == "nginx:latency-histogram" {
  162. 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])) OR sum(rate(nginx_ingress_controller_request_duration_seconds_bucket{status!="404",status!="500",namespace=~"%s",ingress=~"%s"}[5m]))) by (le, ingress))`, opts.Percentile, opts.Namespace, selectionRegex, opts.Namespace, selectionRegex)
  163. } else if opts.Metric == "nginx:status" {
  164. query, err = getNginxStatusQuery(opts, selectionRegex)
  165. if err != nil {
  166. return nil, telemetry.Error(ctx, span, err, "failed to get nginx status query")
  167. }
  168. } else if opts.Metric == "cpu_hpa_threshold" {
  169. // get the name of the kube hpa metric
  170. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  171. cpuMetricName := getKubeCPUMetricName(clientset, service, opts)
  172. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  173. appLabel := ""
  174. if found {
  175. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  176. }
  177. query = createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  178. } else if opts.Metric == "memory_hpa_threshold" {
  179. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  180. memMetricName := getKubeMemoryMetricName(clientset, service, opts)
  181. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  182. appLabel := ""
  183. if found {
  184. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  185. }
  186. query = createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  187. } else if opts.Metric == "hpa_replicas" {
  188. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "status_current_replicas")
  189. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  190. appLabel := ""
  191. if found {
  192. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  193. }
  194. query = createHPACurrentReplicasQuery(metricName, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  195. }
  196. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "query", Value: query})
  197. if opts.ShouldSum {
  198. query = fmt.Sprintf("sum(%s)", query)
  199. }
  200. queryParams := map[string]string{
  201. "query": query,
  202. "start": fmt.Sprintf("%d", opts.StartRange),
  203. "end": fmt.Sprintf("%d", opts.EndRange),
  204. "step": opts.Resolution,
  205. }
  206. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  207. "http",
  208. service.Name,
  209. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  210. "/api/v1/query_range",
  211. queryParams,
  212. )
  213. rawQuery, err := resp.DoRaw(context.TODO())
  214. if err != nil {
  215. // in this case, it's very likely that prometheus doesn't contain any data for the given labels
  216. if strings.Contains(err.Error(), "rejected our request for an unknown reason") {
  217. return []*promParsedSingletonQuery{}, nil
  218. }
  219. return nil, telemetry.Error(ctx, span, err, "failed to get raw query")
  220. }
  221. parsedQuery, err := parseQuery(rawQuery, opts.Metric)
  222. if err != nil {
  223. return nil, telemetry.Error(ctx, span, err, "failed to parse query")
  224. }
  225. return parsedQuery, nil
  226. }
  227. func getNginxStatusQuery(opts *QueryOpts, selectionRegex string) (string, error) {
  228. var queries []string
  229. // we recently changed the way labels are read into prometheus, which has removed the 'exported_' prepended to certain labels
  230. namespaceLabels := []string{"exported_namespace", "namespace"}
  231. for _, namespaceLabel := range namespaceLabels {
  232. queries = append(queries, fmt.Sprintf(`round(sum by (status_code, ingress)(label_replace(increase(nginx_ingress_controller_requests{%s=~"%s",ingress="%s",service="%s"}[2m]), "status_code", "${1}xx", "status", "(.)..")), 0.001)`, namespaceLabel, opts.Namespace, selectionRegex, opts.Name))
  233. }
  234. query := strings.Join(queries, " or ")
  235. return query, nil
  236. }
  237. type promRawQuery struct {
  238. Data struct {
  239. Result []struct {
  240. Metric struct {
  241. Pod string `json:"pod,omitempty"`
  242. StatusCode string `json:"status_code,omitempty"`
  243. } `json:"metric,omitempty"`
  244. Values [][]interface{} `json:"values"`
  245. } `json:"result"`
  246. } `json:"data"`
  247. }
  248. type promParsedSingletonQueryResult struct {
  249. Date interface{} `json:"date,omitempty"`
  250. CPU interface{} `json:"cpu,omitempty"`
  251. Replicas interface{} `json:"replicas,omitempty"`
  252. Memory interface{} `json:"memory,omitempty"`
  253. Bytes interface{} `json:"bytes,omitempty"`
  254. ErrorPct interface{} `json:"error_pct,omitempty"`
  255. Latency interface{} `json:"latency,omitempty"`
  256. StatusCode1xx interface{} `json:"1xx,omitempty"`
  257. StatusCode2xx interface{} `json:"2xx,omitempty"`
  258. StatusCode3xx interface{} `json:"3xx,omitempty"`
  259. StatusCode4xx interface{} `json:"4xx,omitempty"`
  260. StatusCode5xx interface{} `json:"5xx,omitempty"`
  261. }
  262. type promParsedSingletonQuery struct {
  263. Pod string `json:"pod,omitempty"`
  264. Results []promParsedSingletonQueryResult `json:"results"`
  265. }
  266. func parseQuery(rawQuery []byte, metric string) ([]*promParsedSingletonQuery, error) {
  267. if metric == "nginx:status" {
  268. return parseNginxStatusQuery(rawQuery)
  269. }
  270. rawQueryObj := &promRawQuery{}
  271. err := json.Unmarshal(rawQuery, rawQueryObj)
  272. if err != nil {
  273. return nil, err
  274. }
  275. res := make([]*promParsedSingletonQuery, 0)
  276. for _, result := range rawQueryObj.Data.Result {
  277. singleton := &promParsedSingletonQuery{
  278. Pod: result.Metric.Pod,
  279. }
  280. singletonResults := make([]promParsedSingletonQueryResult, 0)
  281. for _, values := range result.Values {
  282. singletonResult := &promParsedSingletonQueryResult{
  283. Date: values[0],
  284. }
  285. if metric == "cpu" {
  286. singletonResult.CPU = values[1]
  287. } else if metric == "memory" {
  288. singletonResult.Memory = values[1]
  289. } else if metric == "network" {
  290. singletonResult.Bytes = values[1]
  291. } else if metric == "nginx:errors" {
  292. singletonResult.ErrorPct = values[1]
  293. } else if metric == "cpu_hpa_threshold" {
  294. singletonResult.CPU = values[1]
  295. } else if metric == "memory_hpa_threshold" {
  296. singletonResult.Memory = values[1]
  297. } else if metric == "hpa_replicas" {
  298. singletonResult.Replicas = values[1]
  299. } else if metric == "nginx:latency" || metric == "nginx:latency-histogram" {
  300. singletonResult.Latency = values[1]
  301. }
  302. singletonResults = append(singletonResults, *singletonResult)
  303. }
  304. singleton.Results = singletonResults
  305. res = append(res, singleton)
  306. }
  307. return res, nil
  308. }
  309. func parseNginxStatusQuery(rawQuery []byte) ([]*promParsedSingletonQuery, error) {
  310. rawQueryObj := &promRawQuery{}
  311. err := json.Unmarshal(rawQuery, rawQueryObj)
  312. if err != nil {
  313. return nil, err
  314. }
  315. singletonResultsByDate := make(map[string]*promParsedSingletonQueryResult, 0)
  316. keys := make([]string, 0)
  317. for _, result := range rawQueryObj.Data.Result {
  318. for _, values := range result.Values {
  319. date := values[0]
  320. dateKey := fmt.Sprintf("%v", date)
  321. if _, ok := singletonResultsByDate[dateKey]; !ok {
  322. keys = append(keys, dateKey)
  323. singletonResultsByDate[dateKey] = &promParsedSingletonQueryResult{
  324. Date: date,
  325. }
  326. }
  327. switch result.Metric.StatusCode {
  328. case "1xx":
  329. singletonResultsByDate[dateKey].StatusCode1xx = values[1]
  330. case "2xx":
  331. singletonResultsByDate[dateKey].StatusCode2xx = values[1]
  332. case "3xx":
  333. singletonResultsByDate[dateKey].StatusCode3xx = values[1]
  334. case "4xx":
  335. singletonResultsByDate[dateKey].StatusCode4xx = values[1]
  336. case "5xx":
  337. singletonResultsByDate[dateKey].StatusCode5xx = values[1]
  338. default:
  339. return nil, errors.New("invalid nginx status code")
  340. }
  341. }
  342. }
  343. sort.Strings(keys)
  344. singletonResults := make([]promParsedSingletonQueryResult, 0)
  345. for _, k := range keys {
  346. singletonResults = append(singletonResults, *singletonResultsByDate[k])
  347. }
  348. singleton := &promParsedSingletonQuery{
  349. Results: singletonResults,
  350. }
  351. res := make([]*promParsedSingletonQuery, 0)
  352. res = append(res, singleton)
  353. return res, nil
  354. }
  355. func getSelectionRegex(kind, name string) (string, error) {
  356. var suffix string
  357. switch strings.ToLower(kind) {
  358. case "deployment":
  359. suffix = "[a-z0-9]+(-[a-z0-9]+)*"
  360. case "statefulset":
  361. suffix = "[0-9]+"
  362. case "job":
  363. suffix = "[a-z0-9]+"
  364. case "cronjob":
  365. suffix = "[a-z0-9]+-[a-z0-9]+"
  366. case "ingress":
  367. return name, nil
  368. case "daemonset":
  369. suffix = "[a-z0-9]+"
  370. default:
  371. return "", fmt.Errorf("not a supported controller to query for metrics")
  372. }
  373. return fmt.Sprintf("%s-%s", name, suffix), nil
  374. }
  375. func createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  376. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  377. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  378. kubeMetricsHPASelectorOne := fmt.Sprintf(
  379. `%s="%s",namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  380. hpaMetricName,
  381. hpaName,
  382. namespace,
  383. )
  384. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  385. `%s="%s",exported_namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  386. hpaMetricName,
  387. hpaName,
  388. namespace,
  389. )
  390. if cpuMetricName == "kube_pod_container_resource_requests" {
  391. kubeMetricsPodSelectorOne += `,resource="cpu",unit="core"`
  392. kubeMetricsPodSelectorTwo += `,resource="cpu",unit="core"`
  393. }
  394. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  395. // as well
  396. if appLabel != "" {
  397. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  398. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  399. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  400. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  401. }
  402. requestCPUOne := fmt.Sprintf(
  403. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  404. hpaMetricName,
  405. cpuMetricName,
  406. kubeMetricsPodSelectorOne,
  407. hpaMetricName,
  408. hpaName,
  409. )
  410. targetCPUUtilThresholdOne := fmt.Sprintf(
  411. `%s{%s} / 50`,
  412. metricName,
  413. kubeMetricsHPASelectorOne,
  414. )
  415. requestCPUTwo := fmt.Sprintf(
  416. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  417. hpaMetricName,
  418. cpuMetricName,
  419. kubeMetricsPodSelectorTwo,
  420. hpaMetricName,
  421. hpaName,
  422. )
  423. targetCPUUtilThresholdTwo := fmt.Sprintf(
  424. `%s{%s} / 50`,
  425. metricName,
  426. kubeMetricsHPASelectorTwo,
  427. )
  428. return fmt.Sprintf(
  429. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  430. requestCPUOne, hpaMetricName, targetCPUUtilThresholdOne,
  431. requestCPUTwo, hpaMetricName, targetCPUUtilThresholdTwo,
  432. )
  433. }
  434. func createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  435. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  436. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  437. kubeMetricsHPASelectorOne := fmt.Sprintf(
  438. `%s="%s",namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  439. hpaMetricName,
  440. hpaName,
  441. namespace,
  442. )
  443. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  444. `%s="%s",exported_namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  445. hpaMetricName,
  446. hpaName,
  447. namespace,
  448. )
  449. if memMetricName == "kube_pod_container_resource_requests" {
  450. kubeMetricsPodSelectorOne += `,resource="memory",unit="byte"`
  451. kubeMetricsPodSelectorTwo += `,resource="memory",unit="byte"`
  452. }
  453. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  454. // as well
  455. if appLabel != "" {
  456. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  457. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  458. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  459. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  460. }
  461. requestMemOne := fmt.Sprintf(
  462. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  463. hpaMetricName,
  464. memMetricName,
  465. kubeMetricsPodSelectorOne,
  466. hpaMetricName,
  467. hpaName,
  468. )
  469. targetMemUtilThresholdOne := fmt.Sprintf(
  470. `%s{%s} / 50`,
  471. metricName,
  472. kubeMetricsHPASelectorOne,
  473. )
  474. requestMemTwo := fmt.Sprintf(
  475. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  476. hpaMetricName,
  477. memMetricName,
  478. kubeMetricsPodSelectorTwo,
  479. hpaMetricName,
  480. hpaName,
  481. )
  482. targetMemUtilThresholdTwo := fmt.Sprintf(
  483. `%s{%s} / 50`,
  484. metricName,
  485. kubeMetricsHPASelectorTwo,
  486. )
  487. return fmt.Sprintf(
  488. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  489. requestMemOne, hpaMetricName, targetMemUtilThresholdOne,
  490. requestMemTwo, hpaMetricName, targetMemUtilThresholdTwo,
  491. )
  492. }
  493. func getKubeMetricsPodSelector(podSelectionRegex, namespace, namespaceLabel string) string {
  494. return fmt.Sprintf(
  495. `pod=~"%s",%s="%s",container!="POD",container!=""`,
  496. podSelectionRegex,
  497. namespaceLabel,
  498. namespace,
  499. )
  500. }
  501. func createHPACurrentReplicasQuery(metricName, hpaName, namespace, appLabel, hpaMetricName string) string {
  502. kubeMetricsHPASelectorOne := fmt.Sprintf(
  503. `%s="%s",namespace="%s"`,
  504. hpaMetricName,
  505. hpaName,
  506. namespace,
  507. )
  508. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  509. `%s="%s",exported_namespace="%s"`,
  510. hpaMetricName,
  511. hpaName,
  512. namespace,
  513. )
  514. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  515. // as well
  516. if appLabel != "" {
  517. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  518. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  519. }
  520. return fmt.Sprintf(
  521. `(%s{%s}) or (%s{%s})`,
  522. metricName,
  523. kubeMetricsHPASelectorOne,
  524. metricName,
  525. kubeMetricsHPASelectorTwo,
  526. )
  527. }
  528. type promRawValuesQuery struct {
  529. Status string `json:"status"`
  530. Data []string `json:"data"`
  531. }
  532. // getKubeHPAMetricName performs a "best guess" for the name of the kube HPA metric,
  533. // which was renamed to kube_horizontalpodautoscaler... in later versions of kube-state-metrics.
  534. // we query Prometheus for a list of metric names to see if any match the new query
  535. // value, otherwise we return the deprecated name.
  536. func getKubeHPAMetricName(
  537. clientset kubernetes.Interface,
  538. service *v1.Service,
  539. opts *QueryOpts,
  540. suffix string,
  541. ) (string, string) {
  542. queryParams := map[string]string{
  543. "match[]": fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix),
  544. "start": fmt.Sprintf("%d", opts.StartRange),
  545. "end": fmt.Sprintf("%d", opts.EndRange),
  546. }
  547. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  548. "http",
  549. service.Name,
  550. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  551. "/api/v1/label/__name__/values",
  552. queryParams,
  553. )
  554. rawQuery, err := resp.DoRaw(context.TODO())
  555. if err != nil {
  556. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  557. }
  558. rawQueryObj := &promRawValuesQuery{}
  559. json.Unmarshal(rawQuery, rawQueryObj)
  560. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  561. return fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix), "horizontalpodautoscaler"
  562. }
  563. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  564. }
  565. func getKubeCPUMetricName(
  566. clientset kubernetes.Interface,
  567. service *v1.Service,
  568. opts *QueryOpts,
  569. ) string {
  570. queryParams := map[string]string{
  571. "match[]": "kube_pod_container_resource_requests",
  572. "start": fmt.Sprintf("%d", opts.StartRange),
  573. "end": fmt.Sprintf("%d", opts.EndRange),
  574. }
  575. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  576. "http",
  577. service.Name,
  578. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  579. "/api/v1/label/__name__/values",
  580. queryParams,
  581. )
  582. rawQuery, err := resp.DoRaw(context.TODO())
  583. if err != nil {
  584. return "kube_pod_container_resource_requests_cpu_cores"
  585. }
  586. rawQueryObj := &promRawValuesQuery{}
  587. json.Unmarshal(rawQuery, rawQueryObj)
  588. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  589. return "kube_pod_container_resource_requests"
  590. }
  591. return "kube_pod_container_resource_requests_cpu_cores"
  592. }
  593. func getKubeMemoryMetricName(
  594. clientset kubernetes.Interface,
  595. service *v1.Service,
  596. opts *QueryOpts,
  597. ) string {
  598. queryParams := map[string]string{
  599. "match[]": "kube_pod_container_resource_requests",
  600. "start": fmt.Sprintf("%d", opts.StartRange),
  601. "end": fmt.Sprintf("%d", opts.EndRange),
  602. }
  603. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  604. "http",
  605. service.Name,
  606. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  607. "/api/v1/label/__name__/values",
  608. queryParams,
  609. )
  610. rawQuery, err := resp.DoRaw(context.TODO())
  611. if err != nil {
  612. return "kube_pod_container_resource_requests_memory_bytes"
  613. }
  614. rawQueryObj := &promRawValuesQuery{}
  615. json.Unmarshal(rawQuery, rawQueryObj)
  616. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  617. return "kube_pod_container_resource_requests"
  618. }
  619. return "kube_pod_container_resource_requests_memory_bytes"
  620. }