Как собирать метрики с приложений, расположенных вне кластера? | 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:
|
Как добавить дополнительные дашборды в вашем проекте? | How do I create custom Grafana dashboards? |
Добавление пользовательских дашбордов для Grafana в Deckhouse реализовано с помощью подхода Infrastructure as a Code.
Чтобы ваш дашборд появился в 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 будет отображаться ваш дашборд. 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 дашборды нельзя изменить через интерфейс Grafana. | System dashboards and dashboards added using GrafanaDashboardDefinition cannot be modified via the Grafana interface. |
Алерты, настроенные в панели dashboard, не работают с шаблонами datasource — такой dashboard является невалидным и не импортируется. В версии Grafana 9.0 функционал legacy alerting был признан устаревшим и заменён на Grafana Alerting. В связи с этим, мы не рекомендуем использовать legacy alerting (оповещения панели мониторинга) в dashboards. | 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. |
Если после применения дашборд не появляется в Grafana, возможно, в JSON файле дашборда присутствует ошибка. Чтобы определить источник проблемы, воспользуйтесь командой | 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 |
Как добавить алерты и/или 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 |
| 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:
|
|
После шага 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: |
Выполните следующие шаги: |
|
| 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:
|
|
Как добавить 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:
|
Создайте кастомный ресурс | 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: |
Подробно о всех параметрах можно прочитать в описании кастомного ресурса 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. |
Создайте кастомный ресурс | 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: |
Подробно о всех параметрах можно прочитать в описании кастомного ресурса 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? |
| 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 секунд. |
|
Как ограничить потребление ресурсов Prometheus? | The most appropriate value for scrapeInterval is in the range of 10-60s. |
Чтобы предотвратить ситуации, когда Variable Policy Agent (VPA) запрашивает у Prometheus или долгосрочного Prometheus больше ресурсов, чем доступно на выделенном узле для этих целей, можно явно установить ограничения для VPA с использованием параметров модуля: | How do I limit Prometheus resource consumption? |
| 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 |
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: |
Как настроить Probe для работы с 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:
|
Добавьте лейбл | How do I set up a Probe to work with Prometheus? |
Пример: | Add the |
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:
| Example: |
Как настроить PrometheusRules для работы с Prometheus? | 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, лейбл | 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 |
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 | Example: |
Выполните следующую команду для просмотра конкретного алерта: | shell |
shell
kubectl get clusteralerts | 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 |
Пример: | Run the following command to view a specific alert: |
shell | shell
kubectl get clusteralerts |
kubectl get clusteralerts 235d4efba7df6af4 -o yaml alert: description: | The recommended course of action:
| Example: |
Присутствие специального алерта | shell |
Как добавить дополнительные эндпоинты в scrape config? | kubectl get clusteralerts 235d4efba7df6af4 -o yaml alert: description: | The recommended course of action:
|
Добавьте в пространство имён, в котором находится ScrapeConfig, лейбл | The presence of a special alert |
Пример: | How do I add additional endpoints to a scrape config? |
yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/scrape-configs-watcher-enabled: “true” | Add the label |
Добавьте ScrapeConfig, который имеет обязательный лейбл | Example: |
yaml apiVersion: monitoring.coreos.com/v1alpha1 kind: ScrapeConfig metadata: name: example-scrape-config namespace: frontend labels: prometheus: main spec: honorLabels: true staticConfigs:
| yamlapiVersion: v1 kind: Namespace metadata: name: frontend labels: prometheus.deckhouse.io/scrape-configs-watcher-enabled: “true” |
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:
| |