async def _check_authentication(self) -> [str, None]: """ Проверка аутентификации по sessionid. По умолчанию продлевает подтвержденную сессию. """ json_message: dict = load_json_template('check_authentication.json', __file__) json_message["params"]["sessionid"] = str(self.auth) check_auth_request = await self.post_to_zabbix_api( error_handling=False, json=json_message) try: auth = check_auth_request['result']['sessionid'] except KeyError: auth = None await self._set_auth(auth) return auth
async def zabbix_login(self): """ Авторизуется на Zabbix через API """ auth = None json_message: dict = load_json_template('user_login.json', __file__) json_message["params"]["user"] = self.username json_message["params"]["password"] = self.password # Метод post_to_zabbix_api проверяет авторизацию и поддерживает ее, вызывая текущий метод. # Если не нужен StackOverflow - отключим проверку авторизации) login_response = await self.post_to_zabbix_api(error_handling=False, json=json_message) try: auth = login_response["result"] except KeyError: self.log.warning('LOGIN FAILED!') await self._set_auth(auth)
async def _execute(self): template = self.template[self.host_name] host = template["host"] message_subject = f"Host info for {host}" message_body = "" main_image = None # Есть сработавшие триггеры? Если да - добавляем кнопки triggers_template = load_template('get_all_problem_triggers.json') triggers_template["params"]["host"] = host triggers = await self.get_data_from_zabbix_api(triggers_template) triggers = triggers['result'] info_triggers = list( filter(lambda x: int(x['priority']) <= 2, triggers)) problem_triggers = list( filter(lambda x: int(x['priority']) > 2, triggers)) if problem_triggers: message_body += \ f">>fire<< <i>Problem-triggers: <b>{len(problem_triggers)}</b></i>\n" self.add_inline_button(GetProblemTriggers, ">>fire<< Bad Triggers", "ge", "3", self.host_name) else: message_body += \ f">>OK<< <i>No problems on line</i>\n" message_body += \ f">>info<< <i>Info-triggers: <b>{len(info_triggers)}</b></i>\n" if info_triggers: self.add_inline_button(GetProblemTriggers, ">>info<< Info Triggers", "le", "2", self.host_name) # Zabbix items? Если да - добавляем их в текст if template["items"]: items_template = load_json_template( 'get_items.json', ZabbixCallableCommand.PATH_TO_FILE) items_template["params"]["itemids"] = template["items"] items = await self.get_data_from_zabbix_api(items_template) items = self.format_items_info(items) message_body += "\n<b>Items overview:</b>\n" message_body += items # Изображение в сообщении? if template["main_image"]: image_type = template["main_image"]["source"] element_id = template["main_image"]["id"] if image_type == "graph": graph_params = self.prepare_query_params(graph_id=element_id) main_image = await self.load_graph(graph_params, image_type) elif image_type == "item": graph_params = self.prepare_query_params(item_id=element_id) main_image = await self.load_graph(graph_params, image_type) else: _LOGGER.warning("Wrong image type!") # Типы графиков указываются в шаблоне команды raise BadCommandTemplateException(self.TMPL_FILE) message_body += "\n<b>Graph:</b>\n" message_body += f">>lupa<< 2h:: {self.reverse_command(GetGraph, image_type, element_id, '2')}\n" message_body += f">>lupa<< 4h:: {self.reverse_command(GetGraph, image_type, element_id, '4')}\n" message_body += f"\n>>repeat<< {self.reverse_command(GetHostInfo, self.host_name)}" # Добавляем кнопки для всех графиков for graph_name, graph_id in template["graphs"].items(): self.add_inline_button(GetGraph, f">>graph1<< {graph_name}", "graph", graph_id) for item_name, item_id in template["item_graphs"].items(): self.add_inline_button(GetGraph, f">>graph2<< {item_name}", "item", item_id) await self.send_message(subject=message_subject, text=message_body, images=[ main_image, ], reply_markup=self.inline_buttons)
def load_template(filename: str) -> dict: return load_json_template(filename, PATH_TO_TEMPLATES)
class GetHostInfo(ZabbixCallableCommandWithArgs, WebInterfaceCommandMixin): """ Get info about Host """ CMD = "hostinfo" JSON_TMPL_FILE = 'host_info.json' HOSTS = { key.capitalize(): value for key, value in load_json_template( JSON_TMPL_FILE, ZabbixCallableCommand.PATH_TO_FILE).items() } ARGS = (arguments.String("host_name", "Zabbix host name", example="Line1", options=list(HOSTS.keys())), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Отображать названия линий на кнопках надо с большой буквы, # но работать команда должна при любом регистре атрибутов self.host_name = self.host_name.strip().lower() self.template = { key.strip().lower(): value for key, value in self.template.items() } async def _execute(self): template = self.template[self.host_name] host = template["host"] message_subject = f"Host info for {host}" message_body = "" main_image = None # Есть сработавшие триггеры? Если да - добавляем кнопки triggers_template = load_template('get_all_problem_triggers.json') triggers_template["params"]["host"] = host triggers = await self.get_data_from_zabbix_api(triggers_template) triggers = triggers['result'] info_triggers = list( filter(lambda x: int(x['priority']) <= 2, triggers)) problem_triggers = list( filter(lambda x: int(x['priority']) > 2, triggers)) if problem_triggers: message_body += \ f">>fire<< <i>Problem-triggers: <b>{len(problem_triggers)}</b></i>\n" self.add_inline_button(GetProblemTriggers, ">>fire<< Bad Triggers", "ge", "3", self.host_name) else: message_body += \ f">>OK<< <i>No problems on line</i>\n" message_body += \ f">>info<< <i>Info-triggers: <b>{len(info_triggers)}</b></i>\n" if info_triggers: self.add_inline_button(GetProblemTriggers, ">>info<< Info Triggers", "le", "2", self.host_name) # Zabbix items? Если да - добавляем их в текст if template["items"]: items_template = load_json_template( 'get_items.json', ZabbixCallableCommand.PATH_TO_FILE) items_template["params"]["itemids"] = template["items"] items = await self.get_data_from_zabbix_api(items_template) items = self.format_items_info(items) message_body += "\n<b>Items overview:</b>\n" message_body += items # Изображение в сообщении? if template["main_image"]: image_type = template["main_image"]["source"] element_id = template["main_image"]["id"] if image_type == "graph": graph_params = self.prepare_query_params(graph_id=element_id) main_image = await self.load_graph(graph_params, image_type) elif image_type == "item": graph_params = self.prepare_query_params(item_id=element_id) main_image = await self.load_graph(graph_params, image_type) else: _LOGGER.warning("Wrong image type!") # Типы графиков указываются в шаблоне команды raise BadCommandTemplateException(self.TMPL_FILE) message_body += "\n<b>Graph:</b>\n" message_body += f">>lupa<< 2h:: {self.reverse_command(GetGraph, image_type, element_id, '2')}\n" message_body += f">>lupa<< 4h:: {self.reverse_command(GetGraph, image_type, element_id, '4')}\n" message_body += f"\n>>repeat<< {self.reverse_command(GetHostInfo, self.host_name)}" # Добавляем кнопки для всех графиков for graph_name, graph_id in template["graphs"].items(): self.add_inline_button(GetGraph, f">>graph1<< {graph_name}", "graph", graph_id) for item_name, item_id in template["item_graphs"].items(): self.add_inline_button(GetGraph, f">>graph2<< {item_name}", "item", item_id) await self.send_message(subject=message_subject, text=message_body, images=[ main_image, ], reply_markup=self.inline_buttons) def _validate(self) -> list: wrong_commands = list() if self.host_name.capitalize() not in self.HOSTS: wrong_commands.append(self.host_name) return wrong_commands