Jump to contentJump to page navigation: previous page [access key p]/next page [access key n]
Aplica-se a SUSE Enterprise Storage 6

7 Monitoramento e alerta

No SUSE Enterprise Storage 6, o DeepSea não implanta mais uma pilha de monitoramento e alerta no master Salt. Os usuários devem definir a função Prometheus para o Prometheus e o Alertmanager, e a função Grafana para o Grafana. Quando vários nós são atribuídos à função Prometheus ou Grafana, uma configuração altamente disponível é implantada.

  • Prometheus é o kit de ferramentas de monitoramento e alerta.

  • O Alertmanager processa os alertas enviados pelo servidor Prometheus.

  • Grafana é o software de visualização e alerta.

  • O prometheus-node_exporter é o serviço executado em todos os minions Salt.

A configuração do Prometheus e os destinos de mineração de dados (daemons de exportação) são definidos automaticamente pelo DeepSea. O DeepSea também implanta uma lista de alertas padrão, por exemplo, health error (erro de saúde), 10% OSDs down (10% dos OSDs inativos) ou pgs inactive (páginas inativas).

7.1 Variáveis do pillar

O pillar Salt é um armazenamento de valor de chave que fornece informações e valores de configuração aos minions. Ele está disponível para todos os minions, cada um com um conteúdo diferente. O pillar Salt já vem preenchido com valores padrão e pode ser personalizado de duas maneiras diferentes:

  • /srv/pillar/ceph/stack/global.yml: mudar as variáveis do pillar de todos os nós.

  • /srv/pillar/ceph/stack/NOME_DO_CLUSTER/minions/HOST: mudar configurações específicas do minion.

Por padrão, as variáveis do pillar abaixo estão disponíveis para todos os nós:

  monitoring:
  alertmanager:
    config: salt://path/to/config
    additional_flags: ''
  grafana:
    ssl_cert: False # self-signed certs are created by default
    ssl_key: False # self-signed certs are created by default
  prometheus:
    # pass additional configration to prometheus
    additional_flags: ''
    alert_relabel_config: []
    rule_files: []
    # per exporter config variables
    scrape_interval:
      ceph: 10
      node_exporter: 10
      prometheus: 10
      grafana: 10
    relabel_config:
      alertmanager: []
      ceph: []
      node_exporter: []
      prometheus: []
      grafana: []
    metric_relabel_config:
      ceph: []
      node_exporter: []
      prometheus: []
      grafana: []
    target_partition:
      ceph: '1/1'
      node_exporter: '1/1'
      prometheus: '1/1'
      grafana: '1/1'

7.2 Grafana

Todo o tráfego é criptografado por meio do Grafana. Você pode fornecer seus próprios certificados SSL ou criar um autoassinado.

O Grafana usa as seguintes variáveis:

  • ssl_cert

  • ssl_key

Para obter mais informações sobre como fornecer seus próprios certificados SSL, consulte a Seção 22.9.1.2, “Certificados assinados por CA”. Se preferir criar o seu certificado, consulte a Seção 22.9.1.1, “Certificados autoassinados”.

7.3 Prometheus

A configuração baseada no exportador que pode ser passada por meio do pillar. Esses grupos são mapeados para os exportadores que fornecem os dados. O exportador de nó está presente em todos os nós; o Ceph é exportado pelos nós do Ceph Manager; o Prometheus e o Grafana são exportados pelos respectivos nós do Prometheus e do Grafana.

O Prometheus usa as seguintes variáveis:

  • scrape_interval: mudar o intervalo de mineração de dados, com que frequência minerar os dados de um exportador.

  • target_partition: destinos de mineração de dados da partição quando várias instâncias do Prometheus são implantadas, e fazer com que algumas instâncias minerem os dados apenas de uma parte de todas as instâncias do exportador.

  • relabel_config: regrava dinamicamente o conjunto de rótulos de um destino antes que seus dados sejam minerados. É possível configurar várias etapas de nova rotulagem por configuração de mineração de dados.

  • metrics_relabel_config: aplicada a amostras como última etapa antes da ingestão.

7.4 Alertmanager

O Alertmanager processa os alertas enviados pelo servidor Prometheus. Ele cuida da eliminação de duplicação, do agrupamento e do processamento deles para o receptor correto. Ele também cuida do silenciamento dos alertas. O Alertmanager é configurado por meio de flags de linha de comando e de um arquivo de configuração, que define as regras de inibição, o roteamento de notificações e os receptores de notificações.

7.4.1 Arquivo de configuração

A configuração do Alertmanager é diferente para cada implantação. Portanto, o DeepSea não inclui nenhum padrão relacionado. Você precisa fornecer seu próprio arquivo de configuração alertmanager.yml. Por padrão, o pacote alertmanager instala um arquivo de configuração /etc/prometheus/alertmanager.yml, que pode servir como configuração de exemplo. Se você preferir que a configuração do Alertmanager seja gerenciada pelo DeepSea, adicione a seguinte chave ao seu pillar, por exemplo, ao arquivo /srv/pillar/ceph/stack/ceph/minions/ID_DO_MINION_DO_MASTER_SALT.sls:

Para ver um exemplo completo de arquivo de configuração do Alertmanager, consulte o Apêndice B, Alertas padrão para o SUSE Enterprise Storage 6.

monitoring:
 alertmanager_config:
   /path/to/your/alertmanager/config.yml

O arquivo de configuração do Alertmanager é gravado no formato YAML. Ele segue o esquema descrito abaixo. Os parâmetros entre colchetes são opcionais. Para parâmetros que não são de lista, o valor padrão é usado. Os seguintes marcadores genéricos são usados no esquema:

DURATION

Uma duração correspondente à expressão regular [0-9]+(ms|[smhdwy])

LABELNAME

Uma string correspondente à expressão regular [a-zA-Z_][a-zA-Z0-9_]*

LABELVALUE

Uma string de caracteres Unicode.

FILEPATH

Um caminho válido no diretório de trabalho atual.

BOOLEANO

Um Booliano que pode assumir o valor "verdadeiro" ou "falso".

STRING

Uma string regular.

SECRET

Uma string regular secreta, por exemplo, uma senha.

TMPL_STRING

Uma string que é expandida para gabarito antes do uso.

TMPL_SECRET

Uma string secreta que é expandida para gabarito antes do uso.

Exemplo 7.1: Configuração global

Os parâmetros na configuração global: são válidos em todos os outros contextos de configuração. Eles também servem como padrão para outras seções da configuração.

global:
# the time after which an alert is declared resolved if it has not been updated
[ resolve_timeout: DURATION | default = 5m ]

# The default SMTP From header field.
[ smtp_from: TMPL_STRING ]
# The default SMTP smarthost used for sending emails, including port number.
# Port number usually is 25, or 587 for SMTP over TLS
# (sometimes referred to as STARTTLS).
# Example: smtp.example.org:587
[ smtp_smarthost: STRING ]
# The default host name to identify to the SMTP server.
[ smtp_hello: STRING | default = "localhost" ]
[ smtp_auth_username: STRING ]
# SMTP Auth using LOGIN and PLAIN.
[ smtp_auth_password: SECRET ]
# SMTP Auth using PLAIN.
[ smtp_auth_identity: STRING ]
# SMTP Auth using CRAM-MD5.
[ smtp_auth_secret: SECRET ]
# The default SMTP TLS requirement.
[ smtp_require_tls: BOOL | default = true ]

# The API URL to use for Slack notifications.
[ slack_api_url: STRING ]
[ victorops_api_key: STRING ]
[ victorops_api_url: STRING | default = "https://victorops.example.com/integrations/alert/" ]
[ pagerduty_url: STRING | default = "https://pagerduty.example.com/v2/enqueue" ]
[ opsgenie_api_key: STRING ]
[ opsgenie_api_url: STRING | default = "https://opsgenie.example.com/" ]
[ hipchat_api_url: STRING | default = "https://hipchat.example.com/" ]
[ hipchat_auth_token: SECRET ]
[ wechat_api_url: STRING | default = "https://wechat.example.com/cgi-bin/" ]
[ wechat_api_secret: SECRET ]
[ wechat_api_corp_id: STRING ]

# The default HTTP client configuration
[ http_config: HTTP_CONFIG ]

# Files from which custom notification template definitions are read.
# The last component may use a wildcard matcher, e.g. 'templates/*.tmpl'.
templates:
[ - FILEPATH ... ]

# The root node of the routing tree.
route: ROUTE

# A list of notification receivers.
receivers:
- RECEIVER ...

# A list of inhibition rules.
inhibit_rules:
[ - INHIBIT_RULE ... ]
Exemplo 7.2: ROUTE

Um bloco ROUTE define um nó em uma árvore de roteamento. Parâmetros não especificados são herdados do seu nó pai. Cada alerta entra na árvore de roteamento na rota de nível superior configurada, que precisa corresponder a todos os alertas. Em seguida, ele atravessa os nós filho. Se a opção continue estiver definida como “false”, a travessia será interrompida após o primeiro filho correspondente. Se a opção for definida como "true" em um nó correspondente, o alerta continuará a correspondência com os irmãos seguintes. Se um alerta não corresponder a nenhum filho de um nó, ele será processado com base nos parâmetros de configuração do nó atual.

[ receiver: STRING ]
[ group_by: '[' LABELNAME, ... ']' ]

# If an alert should continue matching subsequent sibling nodes.
[ continue: BOOLEAN | default = false ]

# A set of equality matchers an alert has to fulfill to match a node.
match:
 [ LABELNAME: LABELVALUE, ... ]

# A set of regex-matchers an alert has to fulfill to match a node.
match_re:
 [ LABELNAME: REGEX, ... ]

# Time to wait before sending a notification for a group of alerts.
[ group_wait: DURATION | default = 30s ]

# Time to wait before sending a notification about new alerts
# added to a group of alerts for which an initial notification has
# already been sent.
[ group_interval: DURATION | default = 5m ]

# Time to wait before re-sending a notification
[ repeat_interval: DURATION | default = 4h ]

# Possible child routes.
routes:
 [ - ROUTE ... ]
Exemplo 7.3: INHIBIT_RULE

Uma regra de inibição silencia um alerta de destino que corresponde a um conjunto de matchers quando existe um alerta de origem que corresponde a outro conjunto de matchers. Os dois alertas precisam compartilhar os mesmos valores de rótulo para os nomes de rótulo na lista equal.

Os alertas podem fazer a correspondência e, portanto, inibir a si mesmos. Não escreva regras de inibição em que um alerta faça a correspondência tanto com a origem quanto com o destino.

# Matchers that need to be fulfilled for the alerts to be muted.
target_match:
 [ LABELNAME: LABELVALUE, ... ]
target_match_re:
 [ LABELNAME: REGEX, ... ]

# Matchers for which at least one alert needs to exist so that the
# inhibition occurs.
source_match:
 [ LABELNAME: LABELVALUE, ... ]
source_match_re:
 [ LABELNAME: REGEX, ... ]

# Labels with an equal value in the source and target
# alert for the inhibition to take effect.
[ equal: '[' LABELNAME, ... ']' ]
Exemplo 7.4: HTTP_CONFIG

HTTP_CONFIG configura o cliente HTTP usado pelo receptor para comunicação com serviços de API.

Observe que as opções basic_auth, bearer_token e bearer_token_file são mutuamente exclusivas.

# Sets the 'Authorization' header with the user name and password.
basic_auth:
[ username: STRING ]
[ password: SECRET ]

# Sets the 'Authorization' header with the bearer token.
[ bearer_token: SECRET ]

# Sets the 'Authorization' header with the bearer token read from a file.
[ bearer_token_file: FILEPATH ]

# TLS settings.
tls_config:
# CA certificate to validate the server certificate with.
[ ca_file: FILEPATH ]
# Certificate and key files for client cert authentication to the server.
[ cert_file: FILEPATH ]
[ key_file: FILEPATH ]
# ServerName extension to indicate the name of the server.
# http://tools.ietf.org/html/rfc4366#section-3.1
[ server_name: STRING ]
# Disable validation of the server certificate.
[ insecure_skip_verify: BOOLEAN | default = false]

# Optional proxy URL.
[ proxy_url: STRING ]
Exemplo 7.5: RECEIVER

O receptor é uma configuração nomeada para uma ou mais integrações de notificação.

Em vez de adicionar novos receptores, recomendamos implementar integrações de notificação personalizadas usando o receptor webhook (consulte o Exemplo 7.15, “WEBHOOK_CONFIG).

# The unique name of the receiver.
name: STRING

# Configurations for several notification integrations.
email_configs:
[ - EMAIL_CONFIG, ... ]
hipchat_configs:
[ - HIPCHAT_CONFIG, ... ]
pagerduty_configs:
[ - PAGERDUTY_CONFIG, ... ]
pushover_configs:
[ - PUSHOVER_CONFIG, ... ]
slack_configs:
[ - SLACK_CONFIG, ... ]
opsgenie_configs:
[ - OPSGENIE_CONFIG, ... ]
webhook_configs:
[ - WEBHOOK_CONFIG, ... ]
victorops_configs:
[ - VICTOROPS_CONFIG, ... ]
wechat_configs:
[ - WECHAT_CONFIG, ... ]
Exemplo 7.6: EMAIL_CONFIG
# Whether to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = false ]

# The email address to send notifications to.
to: TMPL_STRING

# The sender address.
[ from: TMPL_STRING | default = global.smtp_from ]

# The SMTP host through which emails are sent.
[ smarthost: STRING | default = global.smtp_smarthost ]

# The host name to identify to the SMTP server.
[ hello: STRING | default = global.smtp_hello ]

# SMTP authentication details.
[ auth_username: STRING | default = global.smtp_auth_username ]
[ auth_password: SECRET | default = global.smtp_auth_password ]
[ auth_secret: SECRET | default = global.smtp_auth_secret ]
[ auth_identity: STRING | default = global.smtp_auth_identity ]

# The SMTP TLS requirement.
[ require_tls: BOOL | default = global.smtp_require_tls ]

# The HTML body of the email notification.
[ html: TMPL_STRING | default = '{{ template "email.default.html" . }}' ]
# The text body of the email notification.
[ text: TMPL_STRING ]

# Further headers email header key/value pairs. Overrides any headers
# previously set by the notification implementation.
[ headers: { STRING: TMPL_STRING, ... } ]
Exemplo 7.7: HIPCHAT_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = false ]

# The HipChat Room ID.
room_id: TMPL_STRING
# The authentication token.
[ auth_token: SECRET | default = global.hipchat_auth_token ]
# The URL to send API requests to.
[ api_url: STRING | default = global.hipchat_api_url ]

# A label to be shown in addition to the sender's name.
[ from:  TMPL_STRING | default = '{{ template "hipchat.default.from" . }}' ]
# The message body.
[ message:  TMPL_STRING | default = '{{ template "hipchat.default.message" . }}' ]
# Whether this message will trigger a user notification.
[ notify:  BOOLEAN | default = false ]
# Determines how the message is treated by the alertmanager and rendered inside HipChat. Valid values are 'text' and 'html'.
[ message_format:  STRING | default = 'text' ]
# Background color for message.
[ color:  TMPL_STRING | default = '{{ if eq .Status "firing" }}red{{ else }}green{{ end }}' ]

# Configuration of the HTTP client.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.8: PAGERDUTY_CONFIG

As opções routing_key e service_key são mutuamente exclusivas.

# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = true ]

# The PagerDuty integration key (when using 'Events API v2').
routing_key: TMPL_SECRET
# The PagerDuty integration key (when using 'Prometheus').
service_key: TMPL_SECRET

# The URL to send API requests to.
[ url: STRING | default = global.pagerduty_url ]

# The client identification of the Alertmanager.
[ client:  TMPL_STRING | default = '{{ template "pagerduty.default.client" . }}' ]
# A backlink to the notification sender.
[ client_url:  TMPL_STRING | default = '{{ template "pagerduty.default.clientURL" . }}' ]

# The incident description.
[ description: TMPL_STRING | default = '{{ template "pagerduty.default.description" .}}' ]

# Severity of the incident.
[ severity: TMPL_STRING | default = 'error' ]

# A set of arbitrary key/value pairs that provide further details.
[ details: { STRING: TMPL_STRING, ... } | default = {
 firing:       '{{ template "pagerduty.default.instances" .Alerts.Firing }}'
 resolved:     '{{ template "pagerduty.default.instances" .Alerts.Resolved }}'
 num_firing:   '{{ .Alerts.Firing | len }}'
 num_resolved: '{{ .Alerts.Resolved | len }}'
} ]

# The HTTP client's configuration.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.9: PUSHOVER_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = true ]

# The recipient user key.
user_key: SECRET

# Registered application’s API token.
token: SECRET

# Notification title.
[ title: TMPL_STRING | default = '{{ template "pushover.default.title" . }}' ]

# Notification message.
[ message: TMPL_STRING | default = '{{ template "pushover.default.message" . }}' ]

# A supplementary URL displayed together with the message.
[ url: TMPL_STRING | default = '{{ template "pushover.default.url" . }}' ]

# Priority.
[ priority: TMPL_STRING | default = '{{ if eq .Status "firing" }}2{{ else }}0{{ end }}' ]

# How often the Pushover servers will send the same notification (at least 30 seconds).
[ retry: DURATION | default = 1m ]

# How long your notification will continue to be retried (unless the user
# acknowledges the notification).
[ expire: DURATION | default = 1h ]

# Configuration of the HTTP client.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.10: SLACK_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = false ]

# The Slack webhook URL.
[ api_url: SECRET | default = global.slack_api_url ]

# The channel or user to send notifications to.
channel: TMPL_STRING

# API request data as defined by the Slack webhook API.
[ icon_emoji: TMPL_STRING ]
[ icon_url: TMPL_STRING ]
[ link_names: BOOLEAN | default = false ]
[ username: TMPL_STRING | default = '{{ template "slack.default.username" . }}' ]
# The following parameters define the attachment.
actions:
[ ACTION_CONFIG ... ]
[ color: TMPL_STRING | default = '{{ if eq .Status "firing" }}danger{{ else }}good{{ end }}' ]
[ fallback: TMPL_STRING | default = '{{ template "slack.default.fallback" . }}' ]
fields:
[ FIELD_CONFIG ... ]
[ footer: TMPL_STRING | default = '{{ template "slack.default.footer" . }}' ]
[ pretext: TMPL_STRING | default = '{{ template "slack.default.pretext" . }}' ]
[ short_fields: BOOLEAN | default = false ]
[ text: TMPL_STRING | default = '{{ template "slack.default.text" . }}' ]
[ title: TMPL_STRING | default = '{{ template "slack.default.title" . }}' ]
[ title_link: TMPL_STRING | default = '{{ template "slack.default.titlelink" . }}' ]
[ image_url: TMPL_STRING ]
[ thumb_url: TMPL_STRING ]

# Configuration of the HTTP client.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.11: ACTION_CONFIG para SLACK_CONFIG
# Provide a button to tell Slack you want to render a button.
type: TMPL_STRING
# Label for the button.
text: TMPL_STRING
# http or https URL to deliver users to. If you specify invalid URLs, the message will be posted with no button.
url: TMPL_STRING
#  If set to 'primary', the button will be green, indicating the best forward action to take
#  'danger' turns the button red, indicating a destructive action.
[ style: TMPL_STRING [ default = '' ]
Exemplo 7.12: FIELD_CONFIG para SLACK_CONFIG
# A bold heading without markup above the value text.
title: TMPL_STRING
# The text of the field. It can span across several lines.
value: TMPL_STRING
# A flag indicating if value is short enough to be displayed together with other values.
[ short: BOOLEAN | default = slack_config.short_fields ]
Exemplo 7.13: OPSGENIE_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = true ]

# The API key to use with the OpsGenie API.
[ api_key: SECRET | default = global.opsgenie_api_key ]

# The host to send OpsGenie API requests to.
[ api_url: STRING | default = global.opsgenie_api_url ]

# Alert text (maximum is 130 characters).
[ message: TMPL_STRING ]

# A description of the incident.
[ description: TMPL_STRING | default = '{{ template "opsgenie.default.description" . }}' ]

# A backlink to the sender.
[ source: TMPL_STRING | default = '{{ template "opsgenie.default.source" . }}' ]

# A set of arbitrary key/value pairs that provide further detail.
[ details: { STRING: TMPL_STRING, ... } ]

# Comma separated list of team responsible for notifications.
[ teams: TMPL_STRING ]

# Comma separated list of tags attached to the notifications.
[ tags: TMPL_STRING ]

# Additional alert note.
[ note: TMPL_STRING ]

# Priority level of alert, one of P1, P2, P3, P4, and P5.
[ priority: TMPL_STRING ]

# Configuration of the HTTP.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.14: VICTOROPS_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = true ]

# The API key for talking to the VictorOps API.
[ api_key: SECRET | default = global.victorops_api_key ]

# The VictorOps API URL.
[ api_url: STRING | default = global.victorops_api_url ]

# A key used to map the alert to a team.
routing_key: TMPL_STRING

# Describes the behavior of the alert (one of 'CRITICAL', 'WARNING', 'INFO').
[ message_type: TMPL_STRING | default = 'CRITICAL' ]

# Summary of the alerted problem.
[ entity_display_name: TMPL_STRING | default = '{{ template "victorops.default.entity_display_name" . }}' ]

# Long explanation of the alerted problem.
[ state_message: TMPL_STRING | default = '{{ template "victorops.default.state_message" . }}' ]

# The monitoring tool the state message is from.
[ monitoring_tool: TMPL_STRING | default = '{{ template "victorops.default.monitoring_tool" . }}' ]

# Configuration of the HTTP client.
[ http_config: HTTP_CONFIG | default = global.http_config ]
Exemplo 7.15: WEBHOOK_CONFIG

Você pode usar o receptor webhook para configurar um receptor genérico.

# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = true ]

# The endpoint for sending HTTP POST requests.
url: STRING

# Configuration of the HTTP client.
[ http_config: HTTP_CONFIG | default = global.http_config ]

O Alertmanager envia solicitações HTTP POST no seguinte formato JSON:

{
 "version": "4",
 "groupKey": STRING, // identifycation of the group of alerts (to deduplicate)
 "status": "<resolved|firing>",
 "receiver": STRING,
 "groupLabels": OBJECT,
 "commonLabels": OBJECT,
 "commonAnnotations": OBJECT,
 "externalURL": STRING, // backlink to Alertmanager.
 "alerts": [
   {
     "status": "<resolved|firing>",
     "labels": OBJECT,
     "annotations": OBJECT,
     "startsAt": "<rfc3339>",
     "endsAt": "<rfc3339>",
     "generatorURL": STRING // identifies the entity that caused the alert
   },
   ...
 ]
}

O receptor webhook permite a integração com os seguintes mecanismos de notificação:

  • DingTalk (https://github.com/timonwong/prometheus-webhook-dingtalk)

  • IRC Bot (https://github.com/multimfi/bot)

  • JIRAlert (https://github.com/free/jiralert)

  • Phabricator/Maniphest (https://github.com/knyar/phalerts)

  • prom2teams: encaminha notificações às Equipes da Microsoft (https://github.com/idealista/prom2teams)

  • SMS: suporta vários provedores (https://github.com/messagebird/sachet)

  • Telegram bot (https://github.com/inCaller/prometheus_bot)

  • Detecção de SNMP (https://github.com/SUSE/prometheus-webhook-snmp)

Exemplo 7.16: WECHAT_CONFIG
# Whether or not to notify about resolved alerts.
[ send_resolved: BOOLEAN | default = false ]

# The API key to use for the WeChat API.
[ api_secret: SECRET | default = global.wechat_api_secret ]

# The WeChat API URL.
[ api_url: STRING | default = global.wechat_api_url ]

# The corp id used to authenticate.
[ corp_id: STRING | default = global.wechat_api_corp_id ]

# API request data as defined by the WeChat API.
[ message: TMPL_STRING | default = '{{ template "wechat.default.message" . }}' ]
[ agent_id: STRING | default = '{{ template "wechat.default.agent_id" . }}' ]
[ to_user: STRING | default = '{{ template "wechat.default.to_user" . }}' ]
[ to_party: STRING | default = '{{ template "wechat.default.to_party" . }}' ]
[ to_tag: STRING | default = '{{ template "wechat.default.to_tag" . }}' ]

7.4.2 Alertas personalizados

Você pode definir suas condições de alerta personalizado para enviar notificações a um serviço externo. O Prometheus usa sua própria linguagem de expressão para definir alertas personalizados. Veja a seguir um exemplo de regra com um alerta:

groups:
- name: example
 rules:
  # alert on high deviation from average PG count
  - alert: high pg count deviation
   expr: abs(((ceph_osd_pgs > 0) - on (job) group_left avg(ceph_osd_pgs > 0) by (job)) / on (job) group_left avg(ceph_osd_pgs > 0) by (job)) > 0.35
   for: 5m
   labels:
    severity: warning
    type: ses_default
   annotations:
   description: >
    OSD {{ $labels.osd }} deviates by more then 30% from average PG count

A cláusula for opcional especifica o tempo que o Prometheus aguardará ao encontrar pela primeira vez um novo elemento vetor de saída de expressão até contar um alerta como acionado. Neste caso, o Prometheus verificará se o alerta continuará ativo por 5 minutos antes de acionar o alerta. Os elementos no estado pendente estão ativos, mas ainda não foram acionados.

A cláusula labels especifica um conjunto de rótulos adicionais anexados ao alerta. Os rótulos em conflito serão sobregravados. É possível usar rótulos como gabaritos (consulte a Seção 7.4.2.1, “Gabaritos” para obter mais detalhes sobre gabaritos).

A cláusula annotations especifica rótulos informativos. É possível usá-los para armazenar informações adicionais, por exemplo, descrições de alertas ou links de runbook. É possível usar anotações como gabaritos (consulte a Seção 7.4.2.1, “Gabaritos” para obter mais detalhes sobre gabaritos).

Para adicionar alertas personalizados ao SUSE Enterprise Storage 6:

  • armazene os arquivos YAML com alertas personalizados no diretório /etc/prometheus/alerts;

ou

  • insira uma lista de caminhos nos arquivos dos alertas personalizados no Pillar abaixo da chave monitoring:custom_alerts. A Fase 2 do DeepSea ou o comando salt MASTER_SALT state.apply ceph.monitoring.prometheus adicionará os arquivos dos alertas ao local certo.

    Exemplo 7.17: Adição de Alertas Personalizados ao SUSE Enterprise Storage

    Um arquivo com alertas personalizados é armazenado em /root/my_alerts/my_alerts.yml no master Salt. Se você adicionar

    monitoring:
     custom_alerts:
       - /root/my_alerts/my_alerts.yml

    ao arquivo /srv/pillar/ceph/cluster/ID_DO_MINION_DO_MASTER_SALT.sls, o DeepSea criará o arquivo /etc/prometheus/alerts/my_alerts.yml e reiniciará o Prometheus.

7.4.2.1 Gabaritos

Você pode usar gabaritos para valores de rótulo e anotação. A variável $labels inclui os pares de chave/valor do rótulo de uma instância de alerta, enquanto $value inclui o valor avaliado de uma instância de alerta.

O exemplo a seguir insere um rótulo e um valor do elemento de acionamento:

{{ $labels.LABELNAME }}
{{ $value }}

7.4.2.2 Inspecionando alertas em tempo de execução

Se você precisa verificar quais alertas estão ativos, há várias opções:

  • Navegue até a guia Alertas do Prometheus. Nela são mostrados os conjuntos de rótulos exatos nos quais os alertas definidos estão ativos. O Prometheus também armazena séries temporais sintéticas para alertas pendentes e de acionamento. Veja a seguir o formato:

    ALERTS{alertname="ALERT_NAME", alertstate="pending|firing", ADDITIONAL_ALERT_LABELS}

    O valor de amostra será 1 se o alerta for ativo (pendente ou acionamento). A série é marcada como “stale” quando o alerta é inativo.

  • Na interface da Web do Prometheus, no endereço URL http://IP_DO_HOST_PROMETHEUS:9090/alerts, inspecione os alertas e seu estado (INACTIVE, PENDING ou FIRING).

  • Na interface da Web do Alertmanager, no endereço URL http://:IP_DO_HOST_PROMETHEUS9093/#/alerts, inspecione os alertas e silencie-os, se desejado.

7.4.3 Receptor de detecção de SNMP

Para ser notificado sobre alertas do Prometheus por meio de detecções de SNMP, você pode instalar o receptor de detecção de SNMP do Prometheus/Alertmanager por meio do DeepSea. Para isso, você precisa habilitá-lo no Pillar abaixo da chave monitoring:alertmanager_receiver_snmp:enabled. A configuração do receptor deve ser definida abaixo da chave monitoring:alertmanager_receiver_snmp:config. A Fase 2 do DeepSea ou o comando salt MASTER_SALT state.apply ceph.monitoring.alertmanager instalará e configurará o receptor no local apropriado.

Exemplo 7.18: Configuração da Detecção de SNMP
monitoring:
 alertmanager:
   receiver:
      snmp:
        enabled: True
        config:
          host: localhost
          port: 9099
          snmp_host: snmp.foo-bar.com
          snmp_community: private
          metrics: True

Consulte o manual do receptor em https://github.com/SUSE/prometheus-webhook-snmp#global-configuration-file para obter mais detalhes sobre as opções de configuração.

Imprimir esta página