Initial commit: Message Gateway project

- FastAPI приложение для отправки мониторинговых алертов в мессенджеры
- Поддержка Telegram и MAX/VK
- Интеграция с Grafana, Zabbix, AlertManager
- Автоматическое создание тикетов в Jira
- Управление группами мессенджеров через API
- Декораторы для авторизации и скрытия эндпоинтов
- Подробная документация в папке docs/

Автор: Сергей Антропов
Сайт: https://devops.org.ru
This commit is contained in:
2025-11-12 20:25:11 +03:00
commit b90def35ed
72 changed files with 10609 additions and 0 deletions

226
docs/templates.md Normal file
View File

@@ -0,0 +1,226 @@
# Шаблоны сообщений
## Структура шаблонов
Шаблоны сообщений находятся в папке `templates/` и используют синтаксис Jinja2. Шаблоны разделены на две категории:
1. **Шаблоны для мессенджеров** - форматирование сообщений для отправки в Telegram, MAX/VK
2. **Шаблоны для Jira** - форматирование описания тикетов в Jira
## Шаблоны для мессенджеров
### Grafana (`templates/grafana.tmpl`)
Шаблон для форматирования алертов из Grafana:
```jinja2
{{ alert_icon }} <b>{{ title }}</b>
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }}{% endif %}
<b>Подробнее:</b>
{{ message }}
{% if labels %}
👉 <b>Переменные:</b>
{{ labels }}{% endif %}
{% if tags and state !='ok' %}💻 <b>Ответственные:</b>
{{ tags }}{% endif %}
```
**Доступные переменные:**
- `alert_icon` - иконка алерта (🔴, 🟢, 🟡, 🟠, 🔵)
- `status_icon` - иконка статуса (💀, ✅, 🐢, 🤷, 🥴)
- `status_name` - название статуса
- `title` - заголовок алерта
- `message` - сообщение алерта
- `state` - состояние алерта (alerting, ok, paused, pending, no_data)
- `labels` - метрики (evalMatches)
- `tags` - теги алерта
### Zabbix (`templates/zabbix.tmpl`)
Шаблон для форматирования алертов из Zabbix:
```jinja2
{{ alert_icon }} <b>{{ title }}</b>
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }} ({{ state }}){% endif %}
<b>Кратко:</b>
{{ subject }}
<b>Подробнее:</b>
{{ message }}
👉 <b>Значение:</b>
{{ message_data }}
🌐 <b>Сеть:</b>
Хост: {{ label_host }}
IP: {{ label_ip }}
Порт: {{ label_port }}
```
**Доступные переменные:**
- `alert_icon` - иконка алерта
- `status_icon` - иконка статуса
- `status_name` - название статуса
- `title` - название события
- `subject` - тема алерта
- `message` - сообщение алерта
- `message_data` - дополнительные данные события
- `label_host` - имя хоста
- `label_ip` - IP адрес хоста
- `label_port` - порт хоста
### AlertManager (`templates/alertmanager.tmpl`)
Шаблон для форматирования алертов из AlertManager:
```jinja2
{{ alert_icon }} <b>{{ alertname }}</b>
{% if summary is defined %}{{ summary }}{% endif %}
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }}{% endif %}{% if description is defined %}
<b>Подробнее:</b>
{{ description }}{% endif %}{% if another_annotations != "" %}
{{ another_annotations }}{% endif %}
{% if clustername is defined %}👉 <b>Kubernetes:</b>
<b>Кластер</b>: {{ clustername }}{% if node is defined %}
<b>Нода</b>: {{ node }}{% endif %}{% if ns is defined %}
<b>Неймспейс</b>: {{ ns }}{% endif %}{% if deployment is defined %}
<b>Деплоймент</b>: {{ deployment }}{% endif %}{% if daemonset is defined %}
<b>Демонсет</b>: {{ daemonset }}{% endif %}{% if replicaset is defined %}
<b>Репликасет</b>: {{ replicaset }}{% endif %}{% if statefulset is defined %}
<b>Стейтфулсет</b>: {{ statefulset }}{% endif %}{% if container is defined %}
<b>Контейнер</b>: {{ container }}{% endif %}{% if pod is defined %}
<b>Под</b>: {{ pod }}{% endif %}{% if persistentvolumeclaim is defined %}
<b>PVC</b>: {{ persistentvolumeclaim }}{% endif %}{% if job_name is defined %}
<b>Имя джобы</b>: {{ job_name }}{% endif %}{% if job is defined %}
<b>Джоба</b>: {{ job }}{% endif %}{% if reason is defined %}
<b>Причина</b>: {{ reason }}{% endif %}{% if endpoint is defined %}
<b>Эндпоинт</b>: {{ endpoint }}{% endif %}{% if instance is defined %}
<b>Инстанс</b>: {{ instance }}{% endif %}{% if condition is defined %}
<b>Состояние</b>: {{ condition }}{% endif %}{% if reason is defined %}
<b>Причина</b>: {{ reason }}{% endif %}{% endif %}
{% if prometheus is defined %}🔍 <b>Прометей:</b>
<b>Сервер</b>: {{ prometheus }}{% if service is defined %}
<b>Сервис</b>: {{ service }}{% endif %}{% if metrics_path is defined %}
<b>Метрики</b>: {{ metrics_path }}{% endif %}{% if uid is defined %}
<b>UID</b>: {{ uid }}{% endif %}{% if integration is defined %}
<b>Integration</b>: {{ integration }}{% endif %}{% if To is defined %}
<b>To</b>: {{ integration }}{% endif %}{% endif %}
{% if another_labels != "" %}
🤷 <b>Разное</b>:
{{ another_labels }}{% endif %}
```
**Доступные переменные:**
- `alert_icon` - иконка алерта
- `status_icon` - иконка статуса
- `status_name` - название статуса
- `alertname` - название алерта
- `summary` - краткое описание
- `description` - подробное описание
- `another_annotations` - дополнительные аннотации
- `clustername` - имя кластера Kubernetes
- `node` - имя ноды
- `ns` - namespace
- `deployment` - имя deployment
- `pod` - имя pod
- `container` - имя контейнера
- И другие метки из `commonLabels`
## Шаблоны для Jira
### Общий шаблон (`templates/jira_common.tmpl`)
Шаблон для форматирования описания тикетов в Jira:
```jinja2
**Источник:** {{ source }}
{% if k8s_cluster %}**Kubernetes кластер:** {{ k8s_cluster }}{% endif %}
---
## Детали алерта
{% if source == "alertmanager" %}
**Статус:** {{ status }}
**Название:** {{ alertname }}
**Критичность:** {{ severity }}
{% if summary %}**Краткое описание:**
{{ summary }}
{% endif %}
{% if description %}**Подробное описание:**
{{ description }}
{% endif %}
**Метки:**
{% for key, value in common_labels.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
**Аннотации:**
{% for key, value in common_annotations.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
{% endif %}
{% if source == "grafana" %}
**Состояние:** {{ state }}
**Правило:** {{ ruleName }}
**Заголовок:** {{ title }}
{% if message %}**Сообщение:**
{{ message }}
{% endif %}
{% if tags %}**Теги:**
{% for key, value in tags.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
{% endif %}
{% if evalMatches %}**Метрики:**
{% for match in evalMatches %}
- *{{ match.metric }}*: {{ match.value }}
{% endfor %}
{% endif %}
{% endif %}
{% if source == "zabbix" %}
**Статус:** {{ status }}
**Серьезность:** {{ event_severity }}
**Событие:** {{ event_name }}
**Хост:** {{ host_name }} ({{ host_ip }}:{{ host_port }})
**Тема:**
{{ alert_subject }}
**Сообщение:**
{{ alert_message }}
{% endif %}
---
*Тикет создан автоматически системой мониторинга*
```
**Примечания:**
- Шаблон поддерживает условное форматирование в зависимости от источника алерта
- Для каждого источника доступны свои переменные
- Можно создать отдельные шаблоны для каждого источника: `jira_alertmanager.tmpl`, `jira_grafana.tmpl`, `jira_zabbix.tmpl`