from flask import Flask, jsonify, request from drivers.nokia import NokiaDriver from drivers.fiberhome import FiberhomeDriver from config import Config from utils.cache import cache_response import time import json import os app = Flask(__name__) # Carregar inventário de hosts HOSTS_CONFIG = {} if os.path.exists('hosts.json'): with open('hosts.json', 'r') as f: HOSTS_CONFIG = json.load(f) # Mapeamento de drivers DRIVERS = { 'nokia': NokiaDriver, 'fiberhome': FiberhomeDriver } @app.route('/api/v1/olt_stats', methods=['GET']) @cache_response # Cacheia a resposta baseado nos argumentos da request def get_olt_stats(): host_ip = request.args.get('host') driver_name_param = request.args.get('driver') if not host_ip: return jsonify({'error': 'Missing host parameter'}), 400 # Determinar configurações (hosts.json ou defaults) host_config = HOSTS_CONFIG.get(host_ip, {}) # Parâmetros: Preference para query param > hosts.json > default config driver_name = driver_name_param or host_config.get('driver') username = host_config.get('username') or Config.OLT_USERNAME password = host_config.get('password') or Config.OLT_PASSWORD # Opções extras para o driver (ex: ssh_options, snmp_community) # Remove chaves padrão para não duplicar e deixa o resto como opção driver_options = {k: v for k, v in host_config.items() if k not in ['username', 'password', 'driver']} if not driver_name: return jsonify({'error': 'Driver not specified (param or hosts.json)'}), 400 if driver_name not in DRIVERS: return jsonify({'error': f'Driver {driver_name} not supported'}), 400 try: # Instancia o driver com opções extras driver_class = DRIVERS[driver_name] driver = driver_class(host_ip, username, password, **driver_options) # Coleta estatísticas completas (Cards > PONs > ONTs) stats = driver.get_olt_stats() # Estrutura flexível, o driver define o retorno return jsonify(stats) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/health', methods=['GET']) def health_check(): return jsonify({'status': 'ok', 'service': 'IPv0 OLT API', 'version': '3.1'}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5050)