How do I collect metrics from applications running outside of the cluster? | Как собирать метрики с приложений, расположенных вне кластера? |
|
|
|
|
An example | Пример |
Application metrics are freely available (no TLS involved) at | Метрики приложения доступны без TLS, по адресу |
yaml apiVersion: v1 kind: Service metadata: name: my-app namespace: my-namespace labels: prometheus.deckhouse.io/custom-target: my-app spec: ports:
| yaml apiVersion: v1 kind: Service metadata: name: my-app namespace: my-namespace labels: prometheus.deckhouse.io/custom-target: my-app spec: ports:
|
How do I create custom Grafana dashboards? | Как добавить дополнительные дашборды в вашем проекте? |
Custom Grafana dashboards can be added to the project using the Infrastructure as a Code approach.
To add your dashboard to Grafana, create the dedicated | Добавление пользовательских дашбордов для Grafana в Deckhouse реализовано с помощью подхода Infrastructure as a Code.
Чтобы ваш дашборд появился в Grafana, необходимо создать в кластере специальный ресурс — |
An example: | Пример: |
yaml apiVersion: deckhouse.io/v1 kind: GrafanaDashboardDefinition metadata: name: my-dashboard spec: folder: My folder # The folder where the custom dashboard will be located. definition: | { “annotations”: { “list”: [ { “builtIn”: 1, “datasource”: “– Grafana –”, “enable”: true, “hide”: true, “iconColor”: “rgba(0, 211, 255, 1)”, “limit”: 100, … | yaml apiVersion: deckhouse.io/v1 kind: GrafanaDashboardDefinition metadata: name: my-dashboard spec: folder: My folder # Папка, в которой в Grafana будет отображаться ваш дашборд. definition: | { “annotations”: { “list”: [ { “builtIn”: 1, “datasource”: “– Grafana –”, “enable”: true, “hide”: true, “iconColor”: “rgba(0, 211, 255, 1)”, “limit”: 100, … |
System dashboards and dashboards added using GrafanaDashboardDefinition cannot be modified via the Grafana interface. | Системные и добавленные через GrafanaDashboardDefinition дашборды нельзя изменить через интерфейс Grafana. |
Alerts configured in the dashboard do not work with datasource templates - such a dashboard is invalid and cannot be imported. In Grafana 9.0, the legacy alerting functionality was deprecated and replaced with Grafana Alerting. Therefore, we do not recommend using legacy alerting in dashboards. | Алерты, настроенные в панели dashboard, не работают с шаблонами datasource — такой dashboard является невалидным и не импортируется. В версии Grafana 9.0 функционал legacy alerting был признан устаревшим и заменён на Grafana Alerting. В связи с этим, мы не рекомендуем использовать legacy alerting (оповещения панели мониторинга) в dashboards. |
If the dashboard does not appear in Grafana after being applied, there might be an error in the dashboard’s JSON file. To identify the source of the problem, use the command | Если после применения дашборд не появляется в Grafana, возможно, в JSON файле дашборда присутствует ошибка. Чтобы определить источник проблемы, воспользуйтесь командой |
How do I add alerts and/or recording rules? | Как добавить алерты и/или recording-правила для вашего проекта? |
The | Для добавления алертов существует специальный ресурс — |
Parameters: | Параметры: |
|
|
An example: | Пример: |
yaml apiVersion: deckhouse.io/v1 kind: CustomPrometheusRules metadata: name: my-rules spec: groups:
| yaml apiVersion: deckhouse.io/v1 kind: CustomPrometheusRules metadata: name: my-rules spec: groups:
|
How do I provision additional Grafana data sources? | Как подключить дополнительные data source для Grafana? |
The | Для подключения дополнительных data source к Grafana существует специальный ресурс — |
A detailed description of the resource parameters is available in the Grafana documentation. | Параметры ресурса подробно описаны в документации к Grafana. Тип ресурса смотрите в документации по конкретному datasource. |
See the datasource type in the documentation for the specific datasource. | Пример: |
An example: | yaml apiVersion: deckhouse.io/v1 kind: GrafanaAdditionalDatasource metadata: name: another-prometheus spec: type: prometheus access: Proxy url: https://another-prometheus.example.com/prometheus basicAuth: true basicAuthUser: foo jsonData: timeInterval: 30s httpMethod: POST secureJsonData: basicAuthPassword: bar |
yaml apiVersion: deckhouse.io/v1 kind: GrafanaAdditionalDatasource metadata: name: another-prometheus spec: type: prometheus access: Proxy url: https://another-prometheus.example.com/prometheus basicAuth: true basicAuthUser: foo jsonData: timeInterval: 30s httpMethod: POST secureJsonData: basicAuthPassword: bar | Как обеспечить безопасный доступ к метрикам? |
How do I enable secure access to metrics? | Для обеспечения безопасности настоятельно рекомендуем использовать |
To enable secure access to metrics, we strongly recommend using kube-rbac-proxy. | Пример безопасного сбора метрик с приложения, расположенного в кластере |
An example of collecting metrics securely from an application inside a cluster | Чтобы настроить защиту метрик приложения с использованием |
To set up application metrics protection using |
|
| yamlapiVersion: v1 kind: ServiceAccount metadata: name: rbac-proxy-test — apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: rbac-proxy-test roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: d8:rbac-proxy subjects:
|
yamlapiVersion: v1 kind: ServiceAccount metadata: name: rbac-proxy-test — apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: rbac-proxy-test roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: d8:rbac-proxy subjects:
|
|
|
|
| yamlapiVersion: v1 kind: ConfigMap metadata: name: rbac-proxy-config-test namespace: rbac-proxy-test data: config-file.yaml: |+ authorization: resourceAttributes: namespace: default apiVersion: v1 resource: services subresource: proxy name: rbac-proxy-test |
yamlapiVersion: v1 kind: ConfigMap metadata: name: rbac-proxy-config-test namespace: rbac-proxy-test data: config-file.yaml: |+ authorization: resourceAttributes: namespace: default apiVersion: v1 resource: services subresource: proxy name: rbac-proxy-test |
|
|
|
| yamlapiVersion: v1 kind: Service metadata: name: rbac-proxy-test labels: prometheus.deckhouse.io/custom-target: rbac-proxy-test spec: ports:
|
yamlapiVersion: v1 kind: Service metadata: name: rbac-proxy-test labels: prometheus.deckhouse.io/custom-target: rbac-proxy-test spec: ports:
|
|
| yamlapiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: rbac-proxy-test-client rules:
|
yamlapiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: rbac-proxy-test-client rules:
| После шага 4 метрики вашего приложения должны появиться в Prometheus. |
After step 4, your application’s metrics should become available in Prometheus. | Пример безопасного сбора метрик с приложения, расположенного вне кластера |
An example of collecting metrics securely from an application outside a cluster | Предположим, что есть доступный через интернет сервер, на котором работает |
Suppose there is a server exposed to the Internet on which the | Требования: |
Requirements: |
|
| Выполните следующие шаги: |
Follow these steps: |
|
| yamlapiVersion: v1 kind: ServiceAccount metadata: name: prometheus-external-endpoint-server-01 namespace: d8-service-accounts — apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: prometheus-external-endpoint rules:
|
yamlapiVersion: v1 kind: ServiceAccount metadata: name: prometheus-external-endpoint-server-01 namespace: d8-service-accounts — apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: prometheus-external-endpoint rules:
|
|
|
|
|
|
| shell
docker run –network host -d -v ${PWD}/.kube/config:/config quay.io/brancz/kube-rbac-proxy:v0.14.0 –secure-listen-address=0.0.0.0:8443 |
shell
docker run –network host -d -v ${PWD}/.kube/config:/config quay.io/brancz/kube-rbac-proxy:v0.14.0 –secure-listen-address=0.0.0.0:8443 |
|
|
|
| yamlapiVersion: v1 kind: Service metadata: name: prometheus-external-endpoint-server-01 labels: prometheus.deckhouse.io/custom-target: prometheus-external-endpoint-server-01 spec: ports:
|
yamlapiVersion: v1 kind: Service metadata: name: prometheus-external-endpoint-server-01 labels: prometheus.deckhouse.io/custom-target: prometheus-external-endpoint-server-01 spec: ports:
| Как добавить Alertmanager? |
How do I add Alertmanager? | Создайте кастомный ресурс |
Create a custom resource | Пример: |
Example: | yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: webhook spec: type: Internal internal: route: groupBy: [‘job’] groupWait: 30s groupInterval: 5m repeatInterval: 12h receiver: ‘webhook’ receivers:
|
yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: webhook spec: type: Internal internal: route: groupBy: [‘job’] groupWait: 30s groupInterval: 5m repeatInterval: 12h receiver: ‘webhook’ receivers:
| Подробно о всех параметрах можно прочитать в описании кастомного ресурса CustomAlertmanager. |
Refer to the description of the CustomAlertmanager custom resource for more information about the parameters. | Как добавить внешний дополнительный Alertmanager? |
How do I add an additional Alertmanager? | Создайте кастомный ресурс |
Create a custom resource | Пример FQDN Alertmanager: |
FQDN Alertmanager example: | yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-fqdn-alertmanager spec: external: address: https://alertmanager.mycompany.com/myprefix type: External |
yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-fqdn-alertmanager spec: external: address: https://alertmanager.mycompany.com/myprefix type: External | Пример Alertmanager с Kubernetes service: |
Alertmanager with a Kubernetes service: | yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-service-alertmanager spec: external: service: namespace: myns name: my-alertmanager path: /myprefix/ type: External |
yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-service-alertmanager spec: external: service: namespace: myns name: my-alertmanager path: /myprefix/ type: External | Подробно о всех параметрах можно прочитать в описании кастомного ресурса CustomAlertmanager. |
Refer to the description of the CustomAlertmanager Custom Resource for more information about the parameters. | Как в Alertmanager игнорировать лишние алерты? |
How do I ignore unnecessary alerts in Alertmanager? | Решение сводится к настройке маршрутизации алертов в вашем Alertmanager. |
The solution comes down to configuring alert routing in the Alertmanager. | Требования: |
You will need to: |
|
| Ниже приведены примеры настройки |
Below are samples for configuring | Чтобы получать только алерты с лейблами |
Receive all alerts with labels | yaml receivers: Получатель, определенный без параметров, будет работать как “/dev/null”.
|
yaml receivers: The parameterless receiver is similar to “/dev/null”.
| Чтобы получать все алерты, кроме |
Receive all alerts except for | yaml receivers: Получатель, определенный без параметров, будет работать как “/dev/null”.
|
yaml receivers: The parameterless receiver is similar to “/dev/null”.
| С подробным описанием всех параметров можно ознакомиться в официальной документации. |
A detailed description of all parameters can be found in the official documentation. | Почему нельзя установить разный scrapeInterval для отдельных таргетов? |
Why can’t different scrape Intervals be set for individual targets? | Наиболее полный ответ на этот вопрос дает разработчик Prometheus Brian Brazil. Вкратце, разные scrapeInterval’ы принесут следующие проблемы: |
The Prometheus developer Brian Brazil provides, probably, the most comprehensive answer to this question. In short, different scrapeIntervals are likely to cause the following complications: |
|
| Наиболее подходящее значение для scrapeInterval находится в диапазоне 10–60 секунд. |
The most appropriate value for scrapeInterval is in the range of 10-60s. | Как ограничить потребление ресурсов Prometheus? |
How do I limit Prometheus resource consumption? | Чтобы предотвратить ситуации, когда Variable Policy Agent (VPA) запрашивает у Prometheus или долгосрочного Prometheus больше ресурсов, чем доступно на выделенном узле для этих целей, можно явно установить ограничения для VPA с использованием параметров модуля: |
To avoid situations when VPA requests more resources for Prometheus or Longterm Prometheus than those available on the corresponding node, you can explicitly limit VPA using module parameters: |
|
| Как настроить ServiceMonitor или PodMonitor для работы с Prometheus? |
How do I set up a ServiceMonitor or PodMonitor to work with Prometheus? | Добавьте лейбл |
Add the | Пример: |
Example: | yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/monitor-watcher-enabled: “true” — apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: example-app namespace: frontend labels: prometheus: main spec: selector: matchLabels: app: example-app endpoints:
|
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/monitor-watcher-enabled: “true” — apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: example-app namespace: frontend labels: prometheus: main spec: selector: matchLabels: app: example-app endpoints:
| Как настроить Probe для работы с Prometheus? |
How do I set up a Probe to work with Prometheus? | Добавьте лейбл |
Add the | Пример: |
Example: | yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/probe-watcher-enabled: “true” — apiVersion: monitoring.coreos.com/v1 kind: Probe metadata: labels: app: prometheus component: probes prometheus: main name: cdn-is-up namespace: frontend spec: interval: 30s jobName: httpGet module: http_2xx prober: path: /probe scheme: http url: blackbox-exporter.blackbox-exporter.svc.cluster.local:9115 targets: staticConfig: static:
|
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/probe-watcher-enabled: “true” — apiVersion: monitoring.coreos.com/v1 kind: Probe metadata: labels: app: prometheus component: probes prometheus: main name: cdn-is-up namespace: frontend spec: interval: 30s jobName: httpGet module: http_2xx prober: path: /probe scheme: http url: blackbox-exporter.blackbox-exporter.svc.cluster.local:9115 targets: staticConfig: static:
| Как настроить PrometheusRules для работы с Prometheus? |
How do I set up a PrometheusRules to work with Prometheus? | Добавьте в пространство имён, в котором находятся PrometheusRules, лейбл |
Add the label | Пример: |
Example: | yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/rules-watcher-enabled: “true” |
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/rules-watcher-enabled: “true” | Как увеличить размер диска |
How to expand disk size |
|
| Как получить информацию об алертах в кластере? |
How to get information about alerts in a cluster? | Информацию об активных алертах можно получить не только в веб-интерфейсе Grafana/Prometheus, но и в CLI. Это может быть полезным, если у вас есть только доступ к API-серверу кластера и нет возможности открыть веб-интерфейс Grafana/Prometheus. |
You can get information about active alerts not only in the Grafana/Prometheus web interface but in the CLI. This can be useful if you only have access to the cluster API server and there is no way to open the Grafana/Prometheus web interface. | Выполните следующую команду для получения списка алертов в кластере: |
Run the following command to get cluster alerts: | shell kubectl get clusteralerts |
shell kubectl get clusteralerts | Пример вывода: |
Example: | console NAME ALERT SEVERITY AGE LAST RECEIVED STATUS 086551aeee5b5b24 ExtendedMonitoringDeprecatatedAnnotation 4 3h25m 38s firing 226d35c886464d6e ExtendedMonitoringDeprecatatedAnnotation 4 3h25m 38s firing 235d4efba7df6af4 D8SnapshotControllerPodIsNotReady 8 5d4h 44s firing 27464763f0aa857c D8PrometheusOperatorPodIsNotReady 7 5d4h 43s firing ab17837fffa5e440 DeadMansSwitch 4 5d4h 41s firing |
shell | Выполните следующую команду для просмотра конкретного алерта: |
kubectl get clusteralerts NAME ALERT SEVERITY AGE LAST RECEIVED STATUS 086551aeee5b5b24 ExtendedMonitoringDeprecatatedAnnotation 4 3h25m 38s firing 226d35c886464d6e ExtendedMonitoringDeprecatatedAnnotation 4 3h25m 38s firing 235d4efba7df6af4 D8SnapshotControllerPodIsNotReady 8 5d4h 44s firing 27464763f0aa857c D8PrometheusOperatorPodIsNotReady 7 5d4h 43s firing ab17837fffa5e440 DeadMansSwitch 4 5d4h 41s firing | shell
kubectl get clusteralerts |
Run the following command to view a specific alert: | Пример: |
shell
kubectl get clusteralerts | shell |
Example: | kubectl get clusteralerts 235d4efba7df6af4 -o yaml alert: description: | The recommended course of action:
|
shell | Присутствие специального алерта |
kubectl get clusteralerts 235d4efba7df6af4 -o yaml alert: description: | The recommended course of action:
| Как добавить дополнительные эндпоинты в scrape config? |
The presence of a special alert | Добавьте в пространство имён, в котором находится ScrapeConfig, лейбл |
How do I add additional endpoints to a scrape config? | Пример: |
Add the label | yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/scrape-configs-watcher-enabled: “true” |
Example: | Добавьте ScrapeConfig, который имеет обязательный лейбл |
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/scrape-configs-watcher-enabled: “true” | yaml apiVersion: monitoring.coreos.com/v1alpha1 kind: ScrapeConfig metadata: name: example-scrape-config namespace: frontend labels: prometheus: main spec: honorLabels: true staticConfigs:
|
Add the ScrapeConfig with the required label | |
yaml apiVersion: monitoring.coreos.com/v1alpha1 kind: ScrapeConfig metadata: name: example-scrape-config namespace: frontend labels: prometheus: main spec: honorLabels: true staticConfigs:
| |