El AlertManager maneja alertas enviadas por aplicaciones de clientes como el servidor Prometheus. Se encarga de deduplicarlos, agruparlos y enrutarlas a las integraciones del receptor correctas, como correo electrónico, PagerDuty, OpsGenie o muchos otros mecanismos gracias al receptor webhook. También se encarga del silenciamiento e inhibición de alertas.
Hay varias formas de instalar AlertManager.
Los binarios precompilados para las versiones lanzadas están disponibles en la sección de descarga en Prometheus.io. El uso del último binario de lanzamiento de producción es la forma recomendada de instalar AlertManager.
Las imágenes de Docker están disponibles en Quay.io o Docker Hub.
Puede iniciar un contenedor de alertmanager para probarlo con
$ docker run --name alertmanager -d -p 127.0.0.1:9093:9093 quay.io/prometheus/alertmanager
AlertManager ahora se puede alcanzar en http: // localhost: 9093/.
Puedes go get :
$ GO15VENDOREXPERIMENT=1 go get github.com/prometheus/alertmanager/cmd/...
# cd $GOPATH/src/github.com/prometheus/alertmanager
$ alertmanager --config.file=<your_file>
O clonar el repositorio y 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>
También puede construir solo uno de los binarios en este repositorio pasando un nombre a la función de compilación:
$ make build BINARIES=amtool
Esta es una configuración de ejemplo que debería cubrir los aspectos más relevantes del nuevo formato de configuración YAML. La documentación completa de la configuración se puede encontrar aquí.
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> La API actual de AlertManager es la versión 2. Esta API se genera por completo a través del proyecto OpenAPI y vaya a Swagger con la excepción de los propios manejadores HTTP. La especificación API se puede encontrar en API/V2/Openapi.yaml. Aquí se puede acceder a una versión renderizada HTML aquí. Los clientes se pueden generar fácilmente a través de cualquier generador de OpenAPI para todos los idiomas principales.
Con la configuración predeterminada, se accede a los puntos finales en el prefijo A /api/v1 o /api/v2 . El punto final v2 /status sería /api/v2/status . Si --web.route-prefix está configurado, las rutas API también tienen el prefijo con eso, así que --web.route-prefix=/alertmanager/ se relacionaría con /alertmanager/api/v2/status .
API V2 todavía está bajo un gran desarrollo y, por lo tanto, sujeto a cambios.
amtool es una herramienta CLI para interactuar con la API de AlertManager. Está incluido con todos los lanzamientos de AlertManager.
Alternativamente, puede instalar con:
$ go install github.com/prometheus/alertmanager/cmd/amtool@latest
Ver todas las alertas de disparo actualmente:
$ 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!
Ver todas las alertas de disparo actualmente con salida extendida:
$ 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
Además de ver alertas, puede usar la sintaxis de consulta rica proporcionada por 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
Silenciar una 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 silencios:
$ 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
Expirar un silencio:
$ amtool silence expire b3ede22e-ca14-4aa0-932c-ca2f3445f926
Expirar todos los silencios que coincidan con una 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"
Expirar todos los silencios:
$ amtool silence expire $(amtool silence query -q)
Pruebe cómo funciona una plantilla. Digamos que tiene esto en su archivo de configuración:
templates:
- '/foo/bar/*.tmpl'
Luego puede probar cómo se vería una plantilla con el ejemplo usando este comando:
amtool template render --template.glob='/foo/bar/*.tmpl' --template.text='{{ template "slack.default.markdown.v1" . }}'
amtool permite que un archivo de configuración especifique algunas opciones para conveniencia. Las rutas de archivo de configuración predeterminadas son $HOME/.config/amtool/config.yml o /etc/amtool/config.yml
Un archivo de configuración de ejemplo puede parecerse al siguiente:
# 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 le permite visualizar las rutas de su configuración en forma de vista de árbol de texto. También puede usarlo para probar el enrutamiento pasando el conjunto de etiquetas de una alerta e imprime todos los receptores que la alerta coincidiría con ordenar y separar por , (Si usa --verify.receivers Amtool devuelve el código de error 1 en la coincidencia)
Ejemplo 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
La alta disponibilidad de AlertManager está en uso de producción en muchas compañías y está habilitado de forma predeterminada.
IMPORTANTE: Tanto UDP como TCP son necesarios en AlertManager 0.15 y superior para que el clúster funcione.
- Si está utilizando un firewall, asegúrese de la lista blanca del puerto de agrupación para ambos protocolos.
- Si está ejecutando en un contenedor, asegúrese de exponer el puerto de agrupación para ambos protocolos.
Para crear un clúster altamente disponible del alertmanager, las instancias deben configurarse para comunicarse entre sí. Esto se configura utilizando los indicadores --cluster.* .
--cluster.listen-address String: Dirección de escucha de clúster (predeterminado "0.0.0.0:9094"; String vacía deshabilita el modo HA)--cluster.advertise-address String: Dirección de publicidad de clúster--cluster.peer Value: Peers iniciales (repetir el indicador para cada compañero adicional)--cluster.peer-timeout Valor: período de tiempo de tiempo de par (predeterminado "15s")--cluster.gossip-interval Value: Velocidad de propagación de mensajes de clúster (predeterminado "200 ms")--cluster.pushpull-interval Value: los valores más bajos aumentarán las velocidades de convergencia a gastos del ancho de banda (predeterminado "1M0S")--cluster.settle-timeout Valor: tiempo máximo para esperar a que las conexiones de clúster se asientan antes de evaluar las notificaciones.--cluster.tcp-timeout Valor: valor de tiempo de espera para conexiones TCP, lectura y escritura (predeterminada "10s")--cluster.probe-timeout Valor: tiempo para esperar ACK antes de marcar el nodo no saludable (predeterminado "500ms")--cluster.probe-interval Value: Intervalo entre sondas de nodos aleatorios (predeterminado "1s")--cluster.reconnect-interval Valor: intervalo entre intentar volver a conectarse a pares perdidos (predeterminado "10s")--cluster.reconnect-timeout Valor: duración de tiempo para intentar reconectarse en un par perdido (predeterminado: "6h0m0s")--cluster.label Value: la etiqueta es una cadena opcional para incluir en cada paquete y transmisión. Identifica de manera exclusiva el clúster y evita problemas de comunicación cruzada al enviar mensajes de chismes (predeterminado: "") El puerto elegido en la bandera cluster.listen-address es el puerto que debe especificarse en el cluster.peer Flager de los otros pares.
Se requiere el indicador cluster.advertise-address si la instancia no tiene una dirección IP que forma parte de RFC 6890 con una ruta predeterminada.
Para iniciar un grupo de tres pares en su máquina local, use goreman y el procfile dentro de este repositorio.
goreman start
Para señalar su Prometheus 1.4, o más tarde, a múltiples Alertmanagers, configúalos en su archivo de configuración prometheus.yml , por ejemplo:
alerting :
alertmanagers :
- static_configs :
- targets :
- alertmanager1:9093
- alertmanager2:9093
- alertmanager3:9093IMPORTANTE: No cargue el tráfico de equilibrio entre Prometheus y sus Alertmanagerers, sino que apunta a Prometheus a una lista de todos los Alertmanagers. La implementación de AlertManager espera que se envíen todas las alertas a todos los Alertmanagers para garantizar una alta disponibilidad.
Si no se desea ejecutar alertmanager en modo de alta disponibilidad, configurar --cluster.listen-address= evita que AlertManager escuche las solicitudes de pares entrantes.
Consulte la página contribuyente de Prometheus.
Para contribuir a la interfaz de usuario, consulte UI/App/Contrabing.md.
Licencia de Apache 2.0, ver licencia.