metrics.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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: "range", Value: opts.EndRange - opts.StartRange},
  128. telemetry.AttributeKV{Key: "resolution", Value: opts.Resolution},
  129. telemetry.AttributeKV{Key: "percentile", Value: opts.Percentile},
  130. )
  131. if len(service.Spec.Ports) == 0 {
  132. return nil, telemetry.Error(ctx, span, nil, "prometheus service has no exposed ports to query")
  133. }
  134. selectionRegex, err := getSelectionRegex(opts.Kind, opts.Name)
  135. if err != nil {
  136. return nil, telemetry.Error(ctx, span, err, "failed to get selection regex")
  137. }
  138. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "selection-regex", Value: selectionRegex})
  139. var podSelector string
  140. if len(opts.PodList) > 0 {
  141. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, strings.Join(opts.PodList, "|"))
  142. } else {
  143. podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, selectionRegex)
  144. }
  145. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "pod-selector", Value: podSelector})
  146. query := ""
  147. if opts.Metric == "cpu" {
  148. query = fmt.Sprintf("rate(container_cpu_usage_seconds_total{%s}[5m])", podSelector)
  149. } else if opts.Metric == "memory" {
  150. query = fmt.Sprintf("container_memory_usage_bytes{%s}", podSelector)
  151. } else if opts.Metric == "network" {
  152. netPodSelector := fmt.Sprintf(`namespace="%s",pod=~"%s"`, opts.Namespace, selectionRegex)
  153. query = fmt.Sprintf("rate(container_network_receive_bytes_total{%s}[5m])", netPodSelector)
  154. } else if opts.Metric == "nginx:errors" {
  155. 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)
  156. 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)
  157. query = fmt.Sprintf(`%s / %s * 100 OR on() vector(0)`, num, denom)
  158. } else if opts.Metric == "nginx:latency" {
  159. 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)
  160. 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)
  161. query = fmt.Sprintf(`%s / %s OR on() vector(0)`, num, denom)
  162. } else if opts.Metric == "nginx:latency-histogram" {
  163. 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)
  164. } else if opts.Metric == "nginx:status" {
  165. query, err = getNginxStatusQuery(opts, selectionRegex)
  166. if err != nil {
  167. return nil, telemetry.Error(ctx, span, err, "failed to get nginx status query")
  168. }
  169. } else if opts.Metric == "cpu_hpa_threshold" {
  170. // get the name of the kube hpa metric
  171. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  172. cpuMetricName := getKubeCPUMetricName(clientset, service, opts)
  173. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  174. appLabel := ""
  175. if found {
  176. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  177. }
  178. query = createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  179. } else if opts.Metric == "memory_hpa_threshold" {
  180. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
  181. memMetricName := getKubeMemoryMetricName(clientset, service, opts)
  182. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  183. appLabel := ""
  184. if found {
  185. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  186. }
  187. query = createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  188. } else if opts.Metric == "hpa_replicas" {
  189. metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "status_current_replicas")
  190. ksmSvc, found, _ := getKubeStateMetricsService(clientset)
  191. appLabel := ""
  192. if found {
  193. appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
  194. }
  195. query = createHPACurrentReplicasQuery(metricName, opts.Name, opts.Namespace, appLabel, hpaMetricName)
  196. }
  197. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "query", Value: query})
  198. if opts.ShouldSum {
  199. query = fmt.Sprintf("sum(%s)", query)
  200. }
  201. queryParams := map[string]string{
  202. "query": query,
  203. "start": fmt.Sprintf("%d", opts.StartRange),
  204. "end": fmt.Sprintf("%d", opts.EndRange),
  205. "step": opts.Resolution,
  206. }
  207. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  208. "http",
  209. service.Name,
  210. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  211. "/api/v1/query_range",
  212. queryParams,
  213. )
  214. rawQuery, err := resp.DoRaw(ctx)
  215. if err != nil {
  216. // in this case, it's very likely that prometheus doesn't contain any data for the given labels
  217. if strings.Contains(err.Error(), "rejected our request for an unknown reason") {
  218. return []*promParsedSingletonQuery{}, nil
  219. }
  220. return nil, telemetry.Error(ctx, span, err, "failed to get raw query")
  221. }
  222. parsedQuery, err := parseQuery(rawQuery, opts.Metric)
  223. if err != nil {
  224. return nil, telemetry.Error(ctx, span, err, "failed to parse query")
  225. }
  226. return parsedQuery, nil
  227. }
  228. func getNginxStatusQuery(opts *QueryOpts, selectionRegex string) (string, error) {
  229. var queries []string
  230. // we recently changed the way labels are read into prometheus, which has removed the 'exported_' prepended to certain labels
  231. namespaceLabels := []string{"exported_namespace", "namespace"}
  232. for _, namespaceLabel := range namespaceLabels {
  233. 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))
  234. }
  235. query := strings.Join(queries, " or ")
  236. return query, nil
  237. }
  238. type promRawQuery struct {
  239. Data struct {
  240. Result []struct {
  241. Metric struct {
  242. Pod string `json:"pod,omitempty"`
  243. StatusCode string `json:"status_code,omitempty"`
  244. } `json:"metric,omitempty"`
  245. Values [][]interface{} `json:"values"`
  246. } `json:"result"`
  247. } `json:"data"`
  248. }
  249. type promParsedSingletonQueryResult struct {
  250. Date interface{} `json:"date,omitempty"`
  251. CPU interface{} `json:"cpu,omitempty"`
  252. Replicas interface{} `json:"replicas,omitempty"`
  253. Memory interface{} `json:"memory,omitempty"`
  254. Bytes interface{} `json:"bytes,omitempty"`
  255. ErrorPct interface{} `json:"error_pct,omitempty"`
  256. Latency interface{} `json:"latency,omitempty"`
  257. StatusCode1xx interface{} `json:"1xx,omitempty"`
  258. StatusCode2xx interface{} `json:"2xx,omitempty"`
  259. StatusCode3xx interface{} `json:"3xx,omitempty"`
  260. StatusCode4xx interface{} `json:"4xx,omitempty"`
  261. StatusCode5xx interface{} `json:"5xx,omitempty"`
  262. }
  263. type promParsedSingletonQuery struct {
  264. Pod string `json:"pod,omitempty"`
  265. Results []promParsedSingletonQueryResult `json:"results"`
  266. }
  267. func parseQuery(rawQuery []byte, metric string) ([]*promParsedSingletonQuery, error) {
  268. if metric == "nginx:status" {
  269. return parseNginxStatusQuery(rawQuery)
  270. }
  271. rawQueryObj := &promRawQuery{}
  272. err := json.Unmarshal(rawQuery, rawQueryObj)
  273. if err != nil {
  274. return nil, err
  275. }
  276. res := make([]*promParsedSingletonQuery, 0)
  277. for _, result := range rawQueryObj.Data.Result {
  278. singleton := &promParsedSingletonQuery{
  279. Pod: result.Metric.Pod,
  280. }
  281. singletonResults := make([]promParsedSingletonQueryResult, 0)
  282. for _, values := range result.Values {
  283. singletonResult := &promParsedSingletonQueryResult{
  284. Date: values[0],
  285. }
  286. if metric == "cpu" {
  287. singletonResult.CPU = values[1]
  288. } else if metric == "memory" {
  289. singletonResult.Memory = values[1]
  290. } else if metric == "network" {
  291. singletonResult.Bytes = values[1]
  292. } else if metric == "nginx:errors" {
  293. singletonResult.ErrorPct = values[1]
  294. } else if metric == "cpu_hpa_threshold" {
  295. singletonResult.CPU = values[1]
  296. } else if metric == "memory_hpa_threshold" {
  297. singletonResult.Memory = values[1]
  298. } else if metric == "hpa_replicas" {
  299. singletonResult.Replicas = values[1]
  300. } else if metric == "nginx:latency" || metric == "nginx:latency-histogram" {
  301. singletonResult.Latency = values[1]
  302. }
  303. singletonResults = append(singletonResults, *singletonResult)
  304. }
  305. singleton.Results = singletonResults
  306. res = append(res, singleton)
  307. }
  308. return res, nil
  309. }
  310. func parseNginxStatusQuery(rawQuery []byte) ([]*promParsedSingletonQuery, error) {
  311. rawQueryObj := &promRawQuery{}
  312. err := json.Unmarshal(rawQuery, rawQueryObj)
  313. if err != nil {
  314. return nil, err
  315. }
  316. singletonResultsByDate := make(map[string]*promParsedSingletonQueryResult, 0)
  317. keys := make([]string, 0)
  318. for _, result := range rawQueryObj.Data.Result {
  319. for _, values := range result.Values {
  320. date := values[0]
  321. dateKey := fmt.Sprintf("%v", date)
  322. if _, ok := singletonResultsByDate[dateKey]; !ok {
  323. keys = append(keys, dateKey)
  324. singletonResultsByDate[dateKey] = &promParsedSingletonQueryResult{
  325. Date: date,
  326. }
  327. }
  328. switch result.Metric.StatusCode {
  329. case "1xx":
  330. singletonResultsByDate[dateKey].StatusCode1xx = values[1]
  331. case "2xx":
  332. singletonResultsByDate[dateKey].StatusCode2xx = values[1]
  333. case "3xx":
  334. singletonResultsByDate[dateKey].StatusCode3xx = values[1]
  335. case "4xx":
  336. singletonResultsByDate[dateKey].StatusCode4xx = values[1]
  337. case "5xx":
  338. singletonResultsByDate[dateKey].StatusCode5xx = values[1]
  339. default:
  340. return nil, errors.New("invalid nginx status code")
  341. }
  342. }
  343. }
  344. sort.Strings(keys)
  345. singletonResults := make([]promParsedSingletonQueryResult, 0)
  346. for _, k := range keys {
  347. singletonResults = append(singletonResults, *singletonResultsByDate[k])
  348. }
  349. singleton := &promParsedSingletonQuery{
  350. Results: singletonResults,
  351. }
  352. res := make([]*promParsedSingletonQuery, 0)
  353. res = append(res, singleton)
  354. return res, nil
  355. }
  356. func getSelectionRegex(kind, name string) (string, error) {
  357. var suffix string
  358. switch strings.ToLower(kind) {
  359. case "deployment":
  360. suffix = "[a-z0-9]+(-[a-z0-9]+)*"
  361. case "statefulset":
  362. suffix = "[0-9]+"
  363. case "job":
  364. suffix = "[a-z0-9]+"
  365. case "cronjob":
  366. suffix = "[a-z0-9]+-[a-z0-9]+"
  367. case "ingress":
  368. return name, nil
  369. case "daemonset":
  370. suffix = "[a-z0-9]+"
  371. default:
  372. return "", fmt.Errorf("not a supported controller to query for metrics")
  373. }
  374. return fmt.Sprintf("%s-%s", name, suffix), nil
  375. }
  376. func createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  377. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  378. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  379. kubeMetricsHPASelectorOne := fmt.Sprintf(
  380. `%s="%s",namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  381. hpaMetricName,
  382. hpaName,
  383. namespace,
  384. )
  385. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  386. `%s="%s",exported_namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
  387. hpaMetricName,
  388. hpaName,
  389. namespace,
  390. )
  391. if cpuMetricName == "kube_pod_container_resource_requests" {
  392. kubeMetricsPodSelectorOne += `,resource="cpu",unit="core"`
  393. kubeMetricsPodSelectorTwo += `,resource="cpu",unit="core"`
  394. }
  395. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  396. // as well
  397. if appLabel != "" {
  398. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  399. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  400. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  401. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  402. }
  403. requestCPUOne := fmt.Sprintf(
  404. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  405. hpaMetricName,
  406. cpuMetricName,
  407. kubeMetricsPodSelectorOne,
  408. hpaMetricName,
  409. hpaName,
  410. )
  411. targetCPUUtilThresholdOne := fmt.Sprintf(
  412. `%s{%s} / 100`,
  413. metricName,
  414. kubeMetricsHPASelectorOne,
  415. )
  416. requestCPUTwo := fmt.Sprintf(
  417. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  418. hpaMetricName,
  419. cpuMetricName,
  420. kubeMetricsPodSelectorTwo,
  421. hpaMetricName,
  422. hpaName,
  423. )
  424. targetCPUUtilThresholdTwo := fmt.Sprintf(
  425. `%s{%s} / 100`,
  426. metricName,
  427. kubeMetricsHPASelectorTwo,
  428. )
  429. return fmt.Sprintf(
  430. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  431. requestCPUOne, hpaMetricName, targetCPUUtilThresholdOne,
  432. requestCPUTwo, hpaMetricName, targetCPUUtilThresholdTwo,
  433. )
  434. }
  435. func createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
  436. kubeMetricsPodSelectorOne := getKubeMetricsPodSelector(podSelectionRegex, namespace, "namespace")
  437. kubeMetricsPodSelectorTwo := getKubeMetricsPodSelector(podSelectionRegex, namespace, "exported_namespace")
  438. kubeMetricsHPASelectorOne := fmt.Sprintf(
  439. `%s="%s",namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  440. hpaMetricName,
  441. hpaName,
  442. namespace,
  443. )
  444. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  445. `%s="%s",exported_namespace="%s",metric_name="memory",metric_target_type="utilization"`,
  446. hpaMetricName,
  447. hpaName,
  448. namespace,
  449. )
  450. if memMetricName == "kube_pod_container_resource_requests" {
  451. kubeMetricsPodSelectorOne += `,resource="memory",unit="byte"`
  452. kubeMetricsPodSelectorTwo += `,resource="memory",unit="byte"`
  453. }
  454. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  455. // as well
  456. if appLabel != "" {
  457. kubeMetricsPodSelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  458. kubeMetricsPodSelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  459. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  460. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  461. }
  462. requestMemOne := fmt.Sprintf(
  463. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  464. hpaMetricName,
  465. memMetricName,
  466. kubeMetricsPodSelectorOne,
  467. hpaMetricName,
  468. hpaName,
  469. )
  470. targetMemUtilThresholdOne := fmt.Sprintf(
  471. `%s{%s} / 100`,
  472. metricName,
  473. kubeMetricsHPASelectorOne,
  474. )
  475. requestMemTwo := fmt.Sprintf(
  476. `avg by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
  477. hpaMetricName,
  478. memMetricName,
  479. kubeMetricsPodSelectorTwo,
  480. hpaMetricName,
  481. hpaName,
  482. )
  483. targetMemUtilThresholdTwo := fmt.Sprintf(
  484. `%s{%s} / 100`,
  485. metricName,
  486. kubeMetricsHPASelectorTwo,
  487. )
  488. return fmt.Sprintf(
  489. `(%s * on(%s) %s) or (%s * on(%s) %s)`,
  490. requestMemOne, hpaMetricName, targetMemUtilThresholdOne,
  491. requestMemTwo, hpaMetricName, targetMemUtilThresholdTwo,
  492. )
  493. }
  494. func getKubeMetricsPodSelector(podSelectionRegex, namespace, namespaceLabel string) string {
  495. return fmt.Sprintf(
  496. `pod=~"%s",%s="%s",container!="POD",container!=""`,
  497. podSelectionRegex,
  498. namespaceLabel,
  499. namespace,
  500. )
  501. }
  502. func createHPACurrentReplicasQuery(metricName, hpaName, namespace, appLabel, hpaMetricName string) string {
  503. kubeMetricsHPASelectorOne := fmt.Sprintf(
  504. `%s="%s",namespace="%s"`,
  505. hpaMetricName,
  506. hpaName,
  507. namespace,
  508. )
  509. kubeMetricsHPASelectorTwo := fmt.Sprintf(
  510. `%s="%s",exported_namespace="%s"`,
  511. hpaMetricName,
  512. hpaName,
  513. namespace,
  514. )
  515. // the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
  516. // as well
  517. if appLabel != "" {
  518. kubeMetricsHPASelectorOne += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  519. kubeMetricsHPASelectorTwo += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
  520. }
  521. return fmt.Sprintf(
  522. `(%s{%s}) or (%s{%s})`,
  523. metricName,
  524. kubeMetricsHPASelectorOne,
  525. metricName,
  526. kubeMetricsHPASelectorTwo,
  527. )
  528. }
  529. type promRawValuesQuery struct {
  530. Status string `json:"status"`
  531. Data []string `json:"data"`
  532. }
  533. // getKubeHPAMetricName performs a "best guess" for the name of the kube HPA metric,
  534. // which was renamed to kube_horizontalpodautoscaler... in later versions of kube-state-metrics.
  535. // we query Prometheus for a list of metric names to see if any match the new query
  536. // value, otherwise we return the deprecated name.
  537. func getKubeHPAMetricName(
  538. clientset kubernetes.Interface,
  539. service *v1.Service,
  540. opts *QueryOpts,
  541. suffix string,
  542. ) (string, string) {
  543. queryParams := map[string]string{
  544. "match[]": fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix),
  545. "start": fmt.Sprintf("%d", opts.StartRange),
  546. "end": fmt.Sprintf("%d", opts.EndRange),
  547. }
  548. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  549. "http",
  550. service.Name,
  551. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  552. "/api/v1/label/__name__/values",
  553. queryParams,
  554. )
  555. rawQuery, err := resp.DoRaw(context.TODO())
  556. if err != nil {
  557. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  558. }
  559. rawQueryObj := &promRawValuesQuery{}
  560. json.Unmarshal(rawQuery, rawQueryObj)
  561. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  562. return fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix), "horizontalpodautoscaler"
  563. }
  564. return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
  565. }
  566. func getKubeCPUMetricName(
  567. clientset kubernetes.Interface,
  568. service *v1.Service,
  569. opts *QueryOpts,
  570. ) string {
  571. queryParams := map[string]string{
  572. "match[]": "kube_pod_container_resource_requests",
  573. "start": fmt.Sprintf("%d", opts.StartRange),
  574. "end": fmt.Sprintf("%d", opts.EndRange),
  575. }
  576. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  577. "http",
  578. service.Name,
  579. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  580. "/api/v1/label/__name__/values",
  581. queryParams,
  582. )
  583. rawQuery, err := resp.DoRaw(context.TODO())
  584. if err != nil {
  585. return "kube_pod_container_resource_requests_cpu_cores"
  586. }
  587. rawQueryObj := &promRawValuesQuery{}
  588. json.Unmarshal(rawQuery, rawQueryObj)
  589. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  590. return "kube_pod_container_resource_requests"
  591. }
  592. return "kube_pod_container_resource_requests_cpu_cores"
  593. }
  594. func getKubeMemoryMetricName(
  595. clientset kubernetes.Interface,
  596. service *v1.Service,
  597. opts *QueryOpts,
  598. ) string {
  599. queryParams := map[string]string{
  600. "match[]": "kube_pod_container_resource_requests",
  601. "start": fmt.Sprintf("%d", opts.StartRange),
  602. "end": fmt.Sprintf("%d", opts.EndRange),
  603. }
  604. resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
  605. "http",
  606. service.Name,
  607. fmt.Sprintf("%d", service.Spec.Ports[0].Port),
  608. "/api/v1/label/__name__/values",
  609. queryParams,
  610. )
  611. rawQuery, err := resp.DoRaw(context.TODO())
  612. if err != nil {
  613. return "kube_pod_container_resource_requests_memory_bytes"
  614. }
  615. rawQueryObj := &promRawValuesQuery{}
  616. json.Unmarshal(rawQuery, rawQueryObj)
  617. if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
  618. return "kube_pod_container_resource_requests"
  619. }
  620. return "kube_pod_container_resource_requests_memory_bytes"
  621. }