AlertManager обрабатывает оповещения, отправляемые клиентскими приложениями, такими как сервер Прометеуса. Он заботится о дедуплировании, группировке и маршрутизации их в правильных интеграциях приемника, таких как электронная почта, Pagerduty, Opsgenie или многие другие механизмы благодаря приемнику WebHook. Это также заботится о молчании и ингибировании оповещений.
Существуют различные способы установки AlertManager.
Предварительные двоичные файлы для выпущенных версий доступны в разделе загрузки на prometheus.io. Использование последнего производственного выпуска BIRINAR - это рекомендуемый способ установки AlertManager.
Изображения Docker доступны на Quay.io или Docker Hub.
Вы можете запустить контейнер AlertManager, чтобы попробовать его с
$ docker run --name alertmanager -d -p 127.0.0.1:9093:9093 quay.io/prometheus/alertmanager
Alertmanager теперь будет доступен по адресу http: // localhost: 9093/.
Вы можете go get это:
$ GO15VENDOREXPERIMENT=1 go get github.com/prometheus/alertmanager/cmd/...
# cd $GOPATH/src/github.com/prometheus/alertmanager
$ alertmanager --config.file=<your_file>
Или клонировать хранилище и построить вручную:
$ 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>
Вы также можете построить только одну из двоичных файлов в этом репо, передав имя в функцию сборки:
$ make build BINARIES=amtool
Это пример конфигурации, которая должна охватывать наиболее соответствующие аспекты нового формата конфигурации YAML. Полную документацию конфигурации можно найти здесь.
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> Текущий API AlertManager является версией 2. Этот API полностью генерируется с помощью проекта OpenAPI и Go Swagger, за исключением самих HTTP -обработчиков. Спецификация API можно найти в API/V2/openapi.yaml. Здесь можно получить доступ к HTML -версии. Клиенты могут быть легко генерированы через любой генератор OpenAPI для всех основных языков.
С помощью конфигурации по умолчанию доступны конечные точки в соответствии с префиксом A /api/v1 или /api/v2 . Конечная точка V2 /status будет /api/v2/status . Если устанавливается --web.route-prefix , то пути API также префикс с этим также, поэтому --web.route-prefix=/alertmanager/ будет относиться к /alertmanager/api/v2/status .
API V2 по -прежнему находится в тяжелом развитии и, таким образом, подлежит изменению.
amtool - это инструмент CLI для взаимодействия с API AlertManager. Он связан со всеми выпусками Alertmanager.
В качестве альтернативы вы можете установить с:
$ go install github.com/prometheus/alertmanager/cmd/amtool@latest
Просмотреть все в настоящее время увольнения:
$ 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!
Просмотреть все в настоящее время увольнения с расширенным выводом:
$ 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
В дополнение к просмотру оповещений, вы можете использовать богатый синтаксис запросов, предоставленный 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
Молча
$ amtool silence add alertname=Test_Alert
b3ede22e-ca14-4aa0-932c-ca2f3445f926
$ amtool silence add alertname="Test_Alert" instance=~".+0"
e48cb58a-0b17-49ba-b734-3585139b1d25
Просмотреть молчание:
$ 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
Истекает молчание:
$ amtool silence expire b3ede22e-ca14-4aa0-932c-ca2f3445f926
Истекает все молчание, соответствующие запросу:
$ 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"
Истекает все молчание:
$ amtool silence expire $(amtool silence query -q)
Попробуйте, как работает шаблон. Допустим, у вас есть это в вашем файле конфигурации:
templates:
- '/foo/bar/*.tmpl'
Тогда вы можете проверить, как будет выглядеть шаблон с помощью примера, используя эту команду:
amtool template render --template.glob='/foo/bar/*.tmpl' --template.text='{{ template "slack.default.markdown.v1" . }}'
amtool позволяет файлу конфигурации указать некоторые параметры для удобства. Путь файла конфигурации по умолчанию $HOME/.config/amtool/config.yml или /etc/amtool/config.yml
Файл конфигурации примера может выглядеть следующим образом:
# 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 позволяет визуализировать маршруты вашей конфигурации в форме вида текстового дерева. Кроме того, вы можете использовать его для проверки маршрутизации, передавая набор маркировки, и он распечатывает все приемники, которые оповещение будет соответствовать упорядоченным и разделенным , (Если вы используете --verify.receivers amtool возвращает код ошибки 1 при несоответствии)
Пример использования:
# 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
Высокая доступность Alertmanager используется во многих компаниях и включена по умолчанию.
Важно: как UDP, так и TCP необходимы в AlertManager 0,15 и выше для работы кластера.
- Если вы используете брандмауэр, убедитесь, что белый список кластеризации для обоих протоколов.
- Если вы работаете в контейнере, убедитесь, что разоблачайте кластеризационный порт для обоих протоколов.
Чтобы создать очень доступный кластер Alertmanager, экземпляры должны быть настроены для связи друг с другом. Это настроено с использованием флагов --cluster.* .
--cluster.listen-address String: адрес прослушивания кластера (по умолчанию "0.0.0.0:9094"; пустая строка отключает режим HA)--cluster.advertise-address String: Cluster Adderise Addrise--cluster.peer Значение: начальные одноранговые коллеги (повторить флаг для каждого дополнительного сверстника)--cluster.peer-timeout--cluster.gossip-interval : скорость распространения сообщений кластера (по умолчанию "200 мс")--cluster.pushpull-interval : более низкие значения увеличат скорость сходимости за счет полосы пропускания (по умолчанию «1M0S»)--cluster.settle-timeout Out: максимальное время, чтобы подождать, пока кластерные подключения оседают перед оценкой уведомлений.--cluster.tcp-timeout : значение тайм-аута для подключений TCP, чтения и записи (по умолчанию "10s")--cluster.probe-timeout--cluster.probe-interval--cluster.reconnect-interval : интервал между попытками воссоединиться с потерянными коллегами (по умолчанию «10s»)--cluster.reconnect-timeout Out: продолжительность времени попытки воссоединиться с потерянным сверстником (по умолчанию: "6H0M0S")--cluster.label Значение: метка является необязательной строкой для включения в каждый пакет и поток. Он однозначно идентифицирует кластер и предотвращает проблемы между коммуникациями при отправке сообщений о сплетнях (по умолчанию: "") Выбранный порт в флаге cluster.listen-address -это порт, который необходимо указать в cluster.peer Флаг пира других сверстников.
Флаг cluster.advertise-address требуется, если экземпляр не имеет IP-адреса, который является частью RFC 6890 с маршрутом по умолчанию.
Чтобы запустить кластер из трех сверстников на вашей местной машине, используйте goreman и Procfile в этом репозитории.
goreman start
Чтобы указать свой Prometheus 1.4, или позже, экземпляр на несколько AlertManagers, настройте их в вашем файле конфигурации prometheus.yml , например:
alerting :
alertmanagers :
- static_configs :
- targets :
- alertmanager1:9093
- alertmanager2:9093
- alertmanager3:9093ВАЖНО: Не загружайте баланс между Прометеем и его Alertmanagers, а вместо этого укажите Прометею на список всех Alertmanagers. Реализация AlertManager ожидает, что все оповещения будут отправлены всем AlertManagers, чтобы обеспечить высокую доступность.
Если запуск AlertManager в режиме высокой доступности не требуется, настройка --cluster.listen-address= предотвращает прослушивание входящих запросов.
Проверьте страницу Prometheus.
Чтобы внести свой вклад в пользовательский интерфейс, обратитесь к UI/App/Appling.md.
Apache License 2.0, см. Лицензию.