O alertManager lida com alertas enviados por aplicativos de clientes, como o servidor Prometheus. Ele cuida da desduplicação, agrupamento e roteamento para as integrações corretas do receptor, como email, PagerDuty, OpsGenie ou muitos outros mecanismos, graças ao receptor da webhook. Também cuida do silenciamento e inibição dos alertas.
Existem várias maneiras de instalar o AlertManager.
Os binários pré -compilados para versões lançadas estão disponíveis na seção de download no Prometheus.io. Usando o mais recente binário de lançamento de produção é a maneira recomendada de instalar o AlertManager.
As imagens do Docker estão disponíveis no quay.io ou no Hub Docker.
Você pode iniciar um contêiner alertManager para experimentá -lo com
$ docker run --name alertmanager -d -p 127.0.0.1:9093:9093 quay.io/prometheus/alertmanager
O alertManager agora estará acessível em http: // localhost: 9093/.
Você pode go get -lo:
$ GO15VENDOREXPERIMENT=1 go get github.com/prometheus/alertmanager/cmd/...
# cd $GOPATH/src/github.com/prometheus/alertmanager
$ alertmanager --config.file=<your_file>
Ou clonar o repositório e construir manualmente:
$ mkdir -p $GOPATH/src/github.com/prometheus
$ cd $GOPATH/src/github.com/prometheus
$ git clone https://github.com/prometheus/alertmanager.git
$ cd alertmanager
$ make build
$ ./alertmanager --config.file=<your_file>
Você também pode construir apenas um dos binários neste repositório, passando um nome para a função Build:
$ make build BINARIES=amtool
Esta é uma configuração de exemplo que deve cobrir aspectos mais relevantes do novo formato de configuração YAML. A documentação completa da configuração pode ser encontrada aqui.
global :
# The smarthost and SMTP sender used for mail notifications.
smtp_smarthost : ' localhost:25 '
smtp_from : ' [email protected] '
# The root route on which each incoming alert enters.
route :
# The root route must not have any matchers as it is the entry point for
# all alerts. It needs to have a receiver configured so alerts that do not
# match any of the sub-routes are sent to someone.
receiver : ' team-X-mails '
# The labels by which incoming alerts are grouped together. For example,
# multiple alerts coming in for cluster=A and alertname=LatencyHigh would
# be batched into a single group.
#
# To aggregate by all possible labels use '...' as the sole label name.
# This effectively disables aggregation entirely, passing through all
# alerts as-is. This is unlikely to be what you want, unless you have
# a very low alert volume or your upstream notification system performs
# its own grouping. Example: group_by: [...]
group_by : ['alertname', 'cluster']
# When a new group of alerts is created by an incoming alert, wait at
# least 'group_wait' to send the initial notification.
# This way ensures that you get multiple alerts for the same group that start
# firing shortly after another are batched together on the first
# notification.
group_wait : 30s
# When the first notification was sent, wait 'group_interval' to send a batch
# of new alerts that started firing for that group.
group_interval : 5m
# If an alert has successfully been sent, wait 'repeat_interval' to
# resend them.
repeat_interval : 3h
# All the above attributes are inherited by all child routes and can
# overwritten on each.
# The child route trees.
routes :
# This route performs a regular expression match on alert labels to
# catch alerts that are related to a list of services.
- matchers :
- service=~"^(foo1|foo2|baz)$"
receiver : team-X-mails
# The service has a sub-route for critical alerts, any alerts
# that do not match, i.e. severity != critical, fall-back to the
# parent node and are sent to 'team-X-mails'
routes :
- matchers :
- severity="critical"
receiver : team-X-pager
- matchers :
- service="files"
receiver : team-Y-mails
routes :
- matchers :
- severity="critical"
receiver : team-Y-pager
# This route handles all alerts coming from a database service. If there's
# no team to handle it, it defaults to the DB team.
- matchers :
- service="database"
receiver : team-DB-pager
# Also group alerts by affected database.
group_by : [alertname, cluster, database]
routes :
- matchers :
- owner="team-X"
receiver : team-X-pager
- matchers :
- owner="team-Y"
receiver : team-Y-pager
# Inhibition rules allow to mute a set of alerts given that another alert is
# firing.
# We use this to mute any warning-level notifications if the same alert is
# already critical.
inhibit_rules :
- source_matchers :
- severity="critical"
target_matchers :
- severity="warning"
# Apply inhibition if the alertname is the same.
# CAUTION:
# If all label names listed in `equal` are missing
# from both the source and target alerts,
# the inhibition rule will apply!
equal : ['alertname']
receivers :
- name : ' team-X-mails '
email_configs :
- to : ' [email protected], [email protected] '
- name : ' team-X-pager '
email_configs :
- to : ' [email protected] '
pagerduty_configs :
- routing_key : <team-X-key>
- name : ' team-Y-mails '
email_configs :
- to : ' [email protected] '
- name : ' team-Y-pager '
pagerduty_configs :
- routing_key : <team-Y-key>
- name : ' team-DB-pager '
pagerduty_configs :
- routing_key : <team-DB-key> A API ALERTMANAGER atual é a versão 2. Esta API é totalmente gerada pelo projeto OpenAPI e swagger, com exceção dos próprios manipuladores HTTP. A especificação da API pode ser encontrada em API/V2/OpenApi.yaml. Uma versão renderizada HTML pode ser acessada aqui. Os clientes podem ser facilmente gerados por meio de qualquer gerador OpenAPI para todos os principais idiomas.
Com a configuração padrão, os pontos de extremidade são acessados no prefixo A /api/v1 ou /api/v2 . O terminal V2 /status seria /api/v2/status . Se --web.route-prefix estiver definido, as rotas de API também são prefixadas com isso, assim --web.route-prefix=/alertmanager/ se relacionaria com /alertmanager/api/v2/status .
A API V2 ainda está sob desenvolvimento pesado e, portanto, sujeita a mudanças.
amtool é uma ferramenta da CLI para interagir com a API AlertManager. É incluído com todos os lançamentos do AlertManager.
Como alternativa, você pode instalar com:
$ go install github.com/prometheus/alertmanager/cmd/amtool@latest
Ver todos os alertas de disparo atualmente:
$ amtool alert
Alertname Starts At Summary
Test_Alert 2017-08-02 18:30:18 UTC This is a testing alert!
Test_Alert 2017-08-02 18:30:18 UTC This is a testing alert!
Check_Foo_Fails 2017-08-02 18:30:18 UTC This is a testing alert!
Check_Foo_Fails 2017-08-02 18:30:18 UTC This is a testing alert!
Veja todos os alertas atualmente disparando com saída estendida:
$ amtool -o extended alert
Labels Annotations Starts At Ends At Generator URL
alertname="Test_Alert" instance="node0" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
alertname="Test_Alert" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
alertname="Check_Foo_Fails" instance="node0" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
alertname="Check_Foo_Fails" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
Além de visualizar alertas, você pode usar a sintaxe de consulta rica fornecida pelo AlertManager:
$ amtool -o extended alert query alertname="Test_Alert"
Labels Annotations Starts At Ends At Generator URL
alertname="Test_Alert" instance="node0" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
alertname="Test_Alert" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
$ amtool -o extended alert query instance=~".+1"
Labels Annotations Starts At Ends At Generator URL
alertname="Test_Alert" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
alertname="Check_Foo_Fails" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
$ amtool -o extended alert query alertname=~"Test.*" instance=~".+1"
Labels Annotations Starts At Ends At Generator URL
alertname="Test_Alert" instance="node1" link="https://example.com" summary="This is a testing alert!" 2017-08-02 18:31:24 UTC 0001-01-01 00:00:00 UTC http://my.testing.script.local
Silêncio um alerta:
$ amtool silence add alertname=Test_Alert
b3ede22e-ca14-4aa0-932c-ca2f3445f926
$ amtool silence add alertname="Test_Alert" instance=~".+0"
e48cb58a-0b17-49ba-b734-3585139b1d25
Ver silêncios:
$ amtool silence query
ID Matchers Ends At Created By Comment
b3ede22e-ca14-4aa0-932c-ca2f3445f926 alertname=Test_Alert 2017-08-02 19:54:50 UTC kellel
$ amtool silence query instance=~".+0"
ID Matchers Ends At Created By Comment
e48cb58a-0b17-49ba-b734-3585139b1d25 alertname=Test_Alert instance=~.+0 2017-08-02 22:41:39 UTC kellel
Expire um silêncio:
$ amtool silence expire b3ede22e-ca14-4aa0-932c-ca2f3445f926
Expire todos os silêncios que correspondem a uma consulta:
$ amtool silence query instance=~".+0"
ID Matchers Ends At Created By Comment
e48cb58a-0b17-49ba-b734-3585139b1d25 alertname=Test_Alert instance=~.+0 2017-08-02 22:41:39 UTC kellel
$ amtool silence expire $(amtool silence query -q instance=~".+0")
$ amtool silence query instance=~".+0"
Expire todos os silêncios:
$ amtool silence expire $(amtool silence query -q)
Experimente como funciona um modelo. Digamos que você tenha isso em seu arquivo de configuração:
templates:
- '/foo/bar/*.tmpl'
Então você pode testar como seria um modelo com o exemplo usando este comando:
amtool template render --template.glob='/foo/bar/*.tmpl' --template.text='{{ template "slack.default.markdown.v1" . }}'
amtool permite que um arquivo de configuração especifique algumas opções para conveniência. Os caminhos de arquivo de configuração padrão são $HOME/.config/amtool/config.yml ou /etc/amtool/config.yml
Um exemplo de arquivo de configuração pode parecer o seguinte:
# Define the path that `amtool` can find your `alertmanager` instance
alertmanager.url: "http://localhost:9093"
# Override the default author. (unset defaults to your username)
author: [email protected]
# Force amtool to give you an error if you don't include a comment on a silence
comment_required: true
# Set a default output format. (unset defaults to simple)
output: extended
# Set a default receiver
receiver: team-X-pager
amtool permite visualizar as rotas da sua configuração na forma de exibição de árvore de texto. Além disso, você pode usá -lo para testar o roteamento, passando o conjunto de rótulos de um alerta e ele imprime todos os receptores que o alerta corresponderia e separado por , . (Se você usar --verify.receivers , o Amtool retorna o código de erro 1 na incompatibilidade)
Exemplo de uso:
# View routing tree of remote Alertmanager
$ amtool config routes --alertmanager.url=http://localhost:9090
# Test if alert matches expected receiver
$ amtool config routes test --config.file=doc/examples/simple.yml --tree --verify.receivers=team-X-pager service=database owner=team-X
A alta disponibilidade do ALERTMANAGER está no uso da produção em muitas empresas e é ativada por padrão.
IMPORTANTE: Tanto o UDP quanto o TCP são necessários no alertManager 0.15 e superior para o cluster funcionar.
- Se você estiver usando um firewall, certifique -se de colocar a lista de cluster para os dois protocolos.
- Se você estiver em execução em um contêiner, exponha a porta de agrupamento para ambos os protocolos.
Para criar um cluster altamente disponível do alertManager, as instâncias precisam ser configuradas para se comunicar. Isso é configurado usando os sinalizadores --cluster.* .
--cluster.listen-address string: cluster lister endereço (padrão "0.0.0.0:9094"; string vazia desativa o modo HA)--cluster.advertise-address string: endereço de anúncio de cluster--cluster.peer Valor: Pares iniciais (Repita a bandeira para cada par adicional)--cluster.peer-timeout Valor: Período de tempo limite dos colegas (padrão "15s")--cluster.gossip-interval Valor: velocidade de propagação de mensagens de cluster (padrão "200ms")--cluster.pushpull-interval Valor: Valores mais baixos aumentarão as velocidades de convergência às custas da largura de banda (padrão "1M0S")--cluster.settle-timeout Valor: Tempo máximo para aguardar as conexões do cluster para resolver antes de avaliar as notificações.--cluster.tcp-timeout Valor: Valor do tempo limite para conexões TCP, leituras e gravações (padrão "10s")--cluster.probe-timeout Valor: Hora de aguardar o ACK antes de marcar o nó prejudicial (padrão "500ms")--cluster.probe-interval Valor: intervalo entre sondas de nó aleatórias (padrão "1s")--cluster.reconnect-interval Valor: Intervalo entre tentar se reconectar a colegas perdidos (padrão "10s")--cluster.reconnect-timeout Valor: Tempo de tempo para tentar se reconectar a um par perdido (padrão: "6H0M0S")--cluster.label Valor: O rótulo é uma sequência opcional a ser incluída em cada pacote e fluxo. Identifica exclusivamente o cluster e evita problemas de comunicação cruzada ao enviar mensagens de fofocas (padrão: "") A porta escolhida no sinalizador cluster.listen-address é a porta que precisa ser especificada no sinalizador de cluster.peer dos outros pares.
O sinalizador cluster.advertise-address é necessário se a instância não tiver um endereço IP que faça parte do RFC 6890 com uma rota padrão.
Para iniciar um cluster de três colegas em sua máquina local, use goreman e o Procfile neste repositório.
goreman start
Para apontar seu Prometheus 1.4, ou posterior, instância a vários alertmanagers, configure -os no seu arquivo de configuração prometheus.yml , por exemplo:
alerting :
alertmanagers :
- static_configs :
- targets :
- alertmanager1:9093
- alertmanager2:9093
- alertmanager3:9093IMPORTANTE: Não carregue o tráfego do Balanço entre Prometeu e seus alertmanagers, mas aponte Prometeu para uma lista de todos os alertmanagers. A implementação do AlertManager espera que todos os alertas sejam enviados a todos os alertmanagers para garantir alta disponibilidade.
Se a execução do alertManager no modo de alta disponibilidade não for desejada, configurar --cluster.listen-address= impede o alertManager de ouvir solicitações de pares.
Verifique a página que contribui com Prometheus.
Para contribuir para a interface do usuário, consulte a UI/App/Contribuindo.md.
Licença Apache 2.0, consulte a licença.