167 lines
7.4 KiB
Python
167 lines
7.4 KiB
Python
import logging
|
|
import re
|
|
import time
|
|
from datetime import datetime
|
|
from pytz import timezone
|
|
from pyzabbix import ZabbixAPI, ZabbixAPIException
|
|
|
|
import backend_bot
|
|
from config import ZABBIX_URL, ZABBIX_API_TOKEN
|
|
from utilities.telegram_utilities import show_main_menu, escape_telegram_chars
|
|
|
|
zabbix_logger = logging.getLogger("pyzabbix")
|
|
|
|
|
|
def get_triggers_for_group(chat_id, group_id):
|
|
try:
|
|
triggers = get_zabbix_triggers(group_id)
|
|
if not triggers:
|
|
backend_bot.bot.send_message(chat_id, "Нет активных событий.")
|
|
zabbix_logger.debug(f"No active triggers found for group {group_id}.")
|
|
show_main_menu(chat_id)
|
|
else:
|
|
send_triggers_to_user(triggers, chat_id)
|
|
zabbix_logger.debug(f"Sent {len(triggers)} triggers to user {chat_id} for group {group_id}.")
|
|
except ZabbixAPIException as e:
|
|
zabbix_logger.error(f"Zabbix API error for group {group_id}: {e}")
|
|
backend_bot.bot.send_message(chat_id, "Ошибка Zabbix API.")
|
|
show_main_menu(chat_id)
|
|
except Exception as e:
|
|
zabbix_logger.error(f"Error getting triggers for group {group_id}: {e}")
|
|
backend_bot.bot.send_message(chat_id, "Ошибка при получении событий.")
|
|
show_main_menu(chat_id)
|
|
|
|
|
|
def get_triggers_for_all_groups(chat_id, region_id):
|
|
try:
|
|
zapi = ZabbixAPI(ZABBIX_URL)
|
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
|
|
|
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
|
filtered_groups = [group for group in host_groups if 'test' not in group['name'].lower()]
|
|
|
|
all_triggers = []
|
|
for group in filtered_groups:
|
|
try:
|
|
triggers = get_zabbix_triggers(group['groupid'])
|
|
if triggers:
|
|
all_triggers.extend(triggers)
|
|
except ZabbixAPIException as e:
|
|
zabbix_logger.error(f"Zabbix API error for group {group['groupid']} ({group['name']}): {e}")
|
|
backend_bot.bot.send_message(chat_id, f"Ошибка Zabbix API при получении событий для группы {group['name']}.")
|
|
except Exception as e:
|
|
zabbix_logger.error(f"Error getting triggers for group {group['groupid']} ({group['name']}): {e}")
|
|
backend_bot.bot.send_message(chat_id, f"Ошибка при получении событий для группы {group['name']}.")
|
|
|
|
if all_triggers:
|
|
send_triggers_to_user(all_triggers, chat_id)
|
|
zabbix_logger.debug(f"Sent {len(all_triggers)} triggers to user {chat_id} for region {region_id}.")
|
|
else:
|
|
backend_bot.bot.send_message(chat_id, "Нет активных событий.")
|
|
zabbix_logger.debug(f"No active triggers found for region {region_id}.")
|
|
show_main_menu(chat_id)
|
|
except ZabbixAPIException as e:
|
|
zabbix_logger.error(f"Zabbix API error for region {region_id}: {e}")
|
|
backend_bot.bot.send_message(chat_id, "Ошибка Zabbix API.")
|
|
show_main_menu(chat_id)
|
|
except Exception as e:
|
|
zabbix_logger.error(f"Error getting triggers for region {region_id}: {e}")
|
|
backend_bot.bot.send_message(chat_id, "Ошибка при получении событий.")
|
|
show_main_menu(chat_id)
|
|
|
|
|
|
def send_triggers_to_user(triggers, chat_id):
|
|
for trigger in triggers:
|
|
backend_bot.bot.send_message(chat_id, trigger, parse_mode="html")
|
|
time.sleep(1 / 5)
|
|
|
|
|
|
def extract_host_from_name(name):
|
|
match = re.match(r"^(.*?)\s*->", name)
|
|
return match.group(1) if match else "Неизвестный хост"
|
|
|
|
|
|
def get_zabbix_triggers(group_id):
|
|
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
|
start_time = time.time()
|
|
try:
|
|
zapi = ZabbixAPI(ZABBIX_URL)
|
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
|
|
|
problems = zapi.problem.get(
|
|
severities=[4, 5],
|
|
suppressed=0,
|
|
acknowledged=0,
|
|
groupids=group_id
|
|
)
|
|
trigger_ids = [problem["objectid"] for problem in problems]
|
|
|
|
triggers = zapi.trigger.get(
|
|
triggerids=trigger_ids,
|
|
output=["triggerid", "description", "priority"],
|
|
selectHosts=["hostid", "name"],
|
|
monitored=1,
|
|
expandDescription=1,
|
|
expandComment=1,
|
|
selectItems=["itemid", "lastvalue"],
|
|
selectLastEvent=["clock", "eventid"]
|
|
)
|
|
|
|
events = zapi.event.get(
|
|
severities=[4, 5],
|
|
objectids=trigger_ids,
|
|
select_alerts="mediatype"
|
|
)
|
|
|
|
pnet_triggers = []
|
|
event_dict = {event["objectid"]: event for event in events}
|
|
|
|
for trigger in triggers:
|
|
event = event_dict.get(trigger["triggerid"])
|
|
if event:
|
|
for alert in event["alerts"]:
|
|
if alert["mediatypes"] and alert["mediatypes"][0]["name"] in pnet_mediatypes and trigger not in pnet_triggers:
|
|
pnet_triggers.append(trigger)
|
|
break
|
|
|
|
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
|
|
|
zabbix_logger.info(f"Found {len(triggers_sorted)} triggers for group {group_id}.")
|
|
|
|
moskva_tz = timezone('Europe/Moscow')
|
|
priority_map = {'4': 'HIGH', '5': 'DISASTER'}
|
|
trigger_messages = []
|
|
|
|
for trigger in triggers_sorted:
|
|
event_time_epoch = int(trigger['lastEvent']['clock'])
|
|
event_time = datetime.fromtimestamp(event_time_epoch, tz=moskva_tz)
|
|
description = escape_telegram_chars(trigger['description'])
|
|
host = trigger['hosts'][0]['name']
|
|
priority = priority_map.get(trigger['priority'], 'Неизвестно')
|
|
item_ids = [item['itemid'] for item in trigger['items']]
|
|
batchgraph_link = f"{ZABBIX_URL}/history.php?action=batchgraph&"
|
|
batchgraph_link += "&".join([f"itemids[{item_id}]={item_id}" for item_id in item_ids])
|
|
batchgraph_link += "&graphtype=0"
|
|
description = description.replace("{HOST.NAME}", host)
|
|
for i, item in enumerate(trigger['items']):
|
|
lastvalue_placeholder = f"{{ITEM.LASTVALUE{i + 1}}}"
|
|
if lastvalue_placeholder in description:
|
|
description = description.replace(lastvalue_placeholder, item['lastvalue'])
|
|
event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')
|
|
message = (f"<b>Host</b>: {host}\n"
|
|
f"<b>Описание</b>: {description}\n"
|
|
f"<b>Критичность</b>: {priority}\n"
|
|
f"<b>Время создания</b>: {event_time_formatted}\n"
|
|
f'<b>URL</b>: <a href="{batchgraph_link}">Ссылка на график</a>')
|
|
trigger_messages.append(message)
|
|
|
|
end_time = time.time()
|
|
execution_time = end_time - start_time
|
|
zabbix_logger.info(f"Fetched {len(triggers_sorted)} triggers for group {group_id} in {execution_time:.2f} seconds.")
|
|
return trigger_messages
|
|
except ZabbixAPIException as e:
|
|
zabbix_logger.error(f"Zabbix API error for group {group_id}: {e}")
|
|
return None
|
|
except Exception as e:
|
|
zabbix_logger.error(f"Error fetching triggers for group {group_id}: {e}")
|
|
return None |