testes/app/routes/zabbix.py

190 lines
6.3 KiB
Python

from flask import Blueprint, jsonify, request
from flask_mysqldb import MySQL
import requests
import json
from MySQLdb.cursors import DictCursor
zabbix = Blueprint('zabbix', __name__)
mysql = MySQL()
# Função para buscar as configurações dos servidores Zabbix do banco de dados
def get_zabbix_configs():
cursor = mysql.connection.cursor(DictCursor) # Usando DictCursor para retornar dicionários
query = "SELECT * FROM connections_zabbix"
cursor.execute(query)
configs = cursor.fetchall()
cursor.close()
return configs
# Função para autenticar no Zabbix via API JSON-RPC
def zabbix_login(url, username, password):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"username": username,
"password": password
},
"id": 1,
"auth": None
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
result = response.json()
if 'result' in result:
return result['result'] # Retorna o token de autenticação
else:
raise Exception(f"Erro na autenticação: {result}")
# Funções auxiliares para buscar dados no Zabbix
def get_zabbix_host_groups(auth_token, url):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": ["groupid", "name"],
"real_hosts": True
},
"auth": auth_token,
"id": 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json().get("result", [])
def get_zabbix_hosts(auth_token, url, group_id):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"groupids": group_id,
"output": ["hostid", "name"]
},
"auth": auth_token,
"id": 2
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json().get("result", [])
def get_zabbix_items(auth_token, url, host_id):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"hostids": host_id,
"output": ["itemid", "name", "key_"]
},
"auth": auth_token,
"id": 3
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json().get("result", [])
def get_item_data(auth_token, url, item_id):
headers = {'Content-Type': 'application/json-rpc'}
payload = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 0,
"itemids": item_id,
"sortfield": "clock",
"sortorder": "DESC",
"limit": 10
},
"auth": auth_token,
"id": 4
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
return response.json().get("result", [])
# Rota para listar as configurações dos servidores Zabbix
@zabbix.route('/servers', methods=['GET'])
def get_zabbix_servers(data):
try:
zabbix_configs = get_zabbix_configs()
if not zabbix_configs:
return jsonify({"message": "Nenhum servidor Zabbix encontrado"}), 404
servers = [{"name": config['name'], "type": config['type'], "url": config['url']} for config in zabbix_configs]
return jsonify(servers)
except Exception as e:
return jsonify({"error": str(e)}), 500
# Rota para listar os grupos de um servidor específico
@zabbix.route('/<server_name>/groups', methods=['GET'])
def get_host_groups_route(data, server_name):
try:
zabbix_configs = get_zabbix_configs()
config = next((conf for conf in zabbix_configs if conf['name'] == server_name), None)
if config is None:
return jsonify({"error": "Servidor Zabbix não encontrado"}), 404
auth_token = zabbix_login(config['url'], config['username'], config['password'])
groups = get_zabbix_host_groups(auth_token, config['url'])
return jsonify(groups)
except Exception as e:
return jsonify({"error": str(e)}), 500
# Rota para listar os hosts de um grupo específico
@zabbix.route('/<server_name>/groups/<group_id>/hosts', methods=['GET'])
def get_hosts_by_group(data, server_name, group_id):
try:
zabbix_configs = get_zabbix_configs()
config = next((conf for conf in zabbix_configs if conf['name'] == server_name), None)
if config is None:
return jsonify({"error": "Servidor Zabbix não encontrado"}), 404
auth_token = zabbix_login(config['url'], config['username'], config['password'])
hosts = get_zabbix_hosts(auth_token, config['url'], group_id)
return jsonify(hosts)
except Exception as e:
return jsonify({"error": str(e)}), 500
# Rota para listar os itens de um host específico
@zabbix.route('/<server_name>/hosts/<host_id>/items', methods=['GET'])
def get_items_by_host(data, server_name, host_id):
try:
zabbix_configs = get_zabbix_configs()
config = next((conf for conf in zabbix_configs if conf['name'] == server_name), None)
if config is None:
return jsonify({"error": "Servidor Zabbix não encontrado"}), 404
auth_token = zabbix_login(config['url'], config['username'], config['password'])
items = get_zabbix_items(auth_token, config['url'], host_id)
return jsonify(items)
except Exception as e:
return jsonify({"error": str(e)}), 500
# Rota para retornar os dados de um item específico
@zabbix.route('/<server_name>/items/<item_id>/data', methods=['GET'])
def get_item_history_route(data, server_name, item_id):
try:
zabbix_configs = get_zabbix_configs()
config = next((conf for conf in zabbix_configs if conf['name'] == server_name), None)
if config is None:
return jsonify({"error": "Servidor Zabbix não encontrado"}), 404
auth_token = zabbix_login(config['url'], config['username'], config['password'])
item_data = get_item_data(auth_token, config['url'], item_id)
return jsonify(item_data)
except Exception as e:
return jsonify({"error": str(e)}), 500