How do I collect metrics from applications running outside of the cluster? | Как собирать метрики с приложений, расположенных вне кластера? |
|
|
| Пример |
An example | Метрики приложения доступны без TLS, по адресу |
Application metrics are freely available (no TLS involved) at | 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:
| Как добавить дополнительные dashboard’ы в вашем проекте? |
How do I create custom Grafana dashboards? | Добавление пользовательских dashboard’ов для Grafana в Deckhouse реализовано с помощью подхода Infrastructure as a Code.
Чтобы ваш dashboard появился в Grafana, необходимо создать в кластере специальный ресурс — |
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 | Пример: |
An example: | yaml apiVersion: deckhouse.io/v1 kind: GrafanaDashboardDefinition metadata: name: my-dashboard spec: folder: My folder # Папка, в которой в Grafana будет отображаться ваш dashboard. 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 # 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, … | Важно! Системные и добавленные через GrafanaDashboardDefinition dashboard’ы нельзя изменить через интерфейс Grafana. |
| Как добавить алерты и/или recording-правила для вашего проекта? |
How do I add alerts and/or recording rules? | Для добавления алертов существует специальный ресурс — |
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:
| Как подключить дополнительные data source для Grafana? |
How do I provision additional Grafana data sources? | Для подключения дополнительных data source к Grafana существует специальный ресурс — |
The | Параметры ресурса подробно описаны в документации к Grafana. Тип ресурса смотрите в документации по конкретному datasource. |
A detailed description of the resource parameters is available in the Grafana documentation. | Пример: |
See the datasource type in the documentation for the specific datasource. | 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 |
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 | Для обеспечения безопасности настоятельно рекомендуем использовать |
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 |
|
Do the following to set up application metrics protection via the | 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:
|
| После шага 4 метрики вашего приложения должны появиться в Prometheus. |
yamlapiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: rbac-proxy-test-client rules:
| Пример безопасного сбора метрик с приложения, расположенного вне кластера |
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:
| 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:
|
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:
|
|
|
|
| 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:
|
| Как добавить Alertmanager? |
yamlapiVersion: v1 kind: Service metadata: name: prometheus-external-endpoint-server-01 labels: prometheus.deckhouse.io/custom-target: prometheus-external-endpoint-server-01 spec: ports:
| Создайте custom resource |
How do I add Alertmanager? | Пример: |
Create a custom resource | 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:
|
Example: | Подробно о всех параметрах можно прочитать в описании custom resource CustomAlertmanager. |
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:
| Как добавить внешний дополнительный Alertmanager? |
Refer to the description of the CustomAlertmanager custom resource for more information about the parameters. | Создайте custom resource |
How do I add an additional Alertmanager? | Пример FQDN Alertmanager: |
Create a custom resource | yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-fqdn-alertmanager spec: external: address: https://alertmanager.mycompany.com/myprefix type: External |
FQDN Alertmanager example: | Пример Alertmanager с Kubernetes service: |
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-service-alertmanager spec: external: service: namespace: myns name: my-alertmanager path: /myprefix/ type: External |
Alertmanager with a Kubernetes service: | Подробно о всех параметрах можно прочитать в описании custom resource CustomAlertmanager. |
yaml apiVersion: deckhouse.io/v1alpha1 kind: CustomAlertmanager metadata: name: my-service-alertmanager spec: external: service: namespace: myns name: my-alertmanager path: /myprefix/ type: External | Как в Alertmanager игнорировать лишние алерты? |
Refer to the description of the CustomAlertmanager Custom Resource for more information about the parameters. | Решение сводится к настройке маршрутизации алертов в вашем Alertmanager. |
How do I ignore unnecessary alerts in Alertmanager? | Потребуется: |
The solution comes down to configuring alert routing in the Alertmanager. |
|
You will need to: | Ниже приведены примеры настройки |
| Чтобы получать только алерты с лейблами |
Below are samples for configuring | yaml receivers: Получатель, определенный без параметров, будет работать как “/dev/null”.
|
Receive all alerts with labels | Чтобы получать все алерты, кроме |
yaml receivers: The parameterless receiver is similar to “/dev/null”.
| yaml receivers: Получатель, определенный без параметров, будет работать как “/dev/null”.
|
Receive all alerts except for | С подробным описанием всех параметров можно ознакомиться в официальной документации. |
yaml receivers: The parameterless receiver is similar to “/dev/null”.
| Почему нельзя установить разный scrapeInterval для отдельных таргетов? |
A detailed description of all parameters can be found in the official documentation. | Наиболее полный ответ на этот вопрос дает разработчик Prometheus Brian Brazil. Если коротко, разные scrapeInterval’ы принесут следующие проблемы:
|
Why can’t different scrape Intervals be set for individual targets? | Наиболее разумное значение для scrapeInterval находится в диапазоне 10–60 секунд. |
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:
| Как ограничить потребление ресурсов Prometheus? |
The most appropriate value for scrapeInterval is in the range of 10-60s. | Чтобы избежать ситуаций, когда VPA запрашивает для Prometheus или Longterm Prometheus ресурсов больше, чем есть на выделенном для этого узле, можно явно ограничить VPA с помощью параметров модуля:
|
How do I limit Prometheus resource consumption? | Как настроить ServiceMonitor или PodMonitor для работы с Prometheus? |
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:
| Добавьте лейбл |
How do I set up a ServiceMonitor or PodMonitor to work with Prometheus? | Пример: |
Add the | 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:
|
Example: | Как настроить PrometheusRules для работы с Prometheus? |
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:
| Добавьте в namespace, в котором находятся PrometheusRules, лейбл |
How do I set up a PrometheusRules to work with Prometheus? | Пример: |
Add the label | yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/rules-watcher-enabled: “true” |
Example: | Как увеличить размер диска |
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/rules-watcher-enabled: “true” |
|
How to expand disk size | Как получить информацию об алертах в кластере? |
| Информацию об активных алертах можно получить не только в веб-интерфейсе Grafana/Prometheus, но и в CLI. Это может быть полезным, если у вас есть только доступ к API-серверу кластера и нет возможности открыть веб-интерфейс Grafana/Prometheus. |
How to get information about alerts in a cluster? | Выполните следующую команду для получения списка алертов в кластере: |
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. | shell kubectl get clusteralerts |
Run the following command to get cluster alerts: | Пример: |
shell kubectl get clusteralerts | shell |
Example: | 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 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? |
Remember the special alert | Добавьте в namespace, в котором находится 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:
| |