sorted code
This commit is contained in:
97
app.py
97
app.py
@ -1,35 +1,37 @@
|
||||
from flask import Flask, render_template, jsonify
|
||||
import subprocess
|
||||
import platform
|
||||
import logging
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from flask import Flask, render_template, jsonify
|
||||
import requests
|
||||
from urllib3.exceptions import InsecureRequestWarning
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Disable InsecureRequestWarning
|
||||
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
||||
|
||||
# Initialize Flask app
|
||||
app = Flask(__name__)
|
||||
|
||||
def ping(host):
|
||||
param = '-n' if platform.system().lower() == 'windows' else '-c'
|
||||
command = ['ping', param, '1', host]
|
||||
return subprocess.call(command, stdout=subprocess.DEVNULL) == 0
|
||||
# Global state
|
||||
device_status = {}
|
||||
|
||||
# Configuration functions
|
||||
def load_config():
|
||||
with open('config.json') as f:
|
||||
return json.load(f)
|
||||
|
||||
device_status = {}
|
||||
def update_status():
|
||||
while True:
|
||||
config = load_config()
|
||||
for device in config['devices']:
|
||||
current_status = ping(device['ip'])
|
||||
previous_status = device_status.get(device['name'], True)
|
||||
|
||||
if current_status != previous_status:
|
||||
diagnostics = run_diagnostics(device)
|
||||
send_webhook(device, current_status, diagnostics)
|
||||
|
||||
device_status[device['name']] = current_status
|
||||
time.sleep(config['check_interval'])
|
||||
# Network utility functions
|
||||
def ping(host):
|
||||
param = '-n' if platform.system().lower() == 'windows' else '-c'
|
||||
command = ['ping', param, '1', host]
|
||||
return subprocess.call(command, stdout=subprocess.DEVNULL) == 0
|
||||
|
||||
def send_webhook(device, status, diagnostics):
|
||||
config = load_config()
|
||||
@ -41,10 +43,7 @@ def send_webhook(device, status, diagnostics):
|
||||
}
|
||||
requests.post(config['webhook_url'], json=webhook_data)
|
||||
|
||||
import requests
|
||||
from urllib3.exceptions import InsecureRequestWarning
|
||||
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
||||
|
||||
# UniFi API integration
|
||||
class UnifiAPI:
|
||||
def __init__(self, config):
|
||||
self.base_url = config['unifi']['controller']
|
||||
@ -65,7 +64,7 @@ class UnifiAPI:
|
||||
except requests.exceptions.RequestException as e:
|
||||
logging.error(f"Failed to get device details: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def get_device_diagnostics(self, device):
|
||||
details = self.get_device_details(device['device_id'])
|
||||
if not details:
|
||||
@ -88,7 +87,6 @@ class UnifiAPI:
|
||||
'interfaces': {}
|
||||
}
|
||||
|
||||
# Add interface details
|
||||
if 'interfaces' in details:
|
||||
diagnostics['interfaces'] = self._parse_interfaces(details['interfaces'])
|
||||
|
||||
@ -119,8 +117,7 @@ class UnifiAPI:
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
# Monitoring functions
|
||||
def run_diagnostics(device):
|
||||
config = load_config()
|
||||
unifi = UnifiAPI(config)
|
||||
@ -134,6 +131,31 @@ def run_diagnostics(device):
|
||||
|
||||
return diagnostics
|
||||
|
||||
def update_status():
|
||||
while True:
|
||||
config = load_config()
|
||||
for device in config['devices']:
|
||||
current_status = ping(device['ip'])
|
||||
previous_status = device_status.get(device['name'], True)
|
||||
|
||||
if current_status != previous_status:
|
||||
diagnostics = run_diagnostics(device)
|
||||
send_webhook(device, current_status, diagnostics)
|
||||
|
||||
device_status[device['name']] = current_status
|
||||
time.sleep(config['check_interval'])
|
||||
|
||||
# Flask routes
|
||||
@app.route('/')
|
||||
def home():
|
||||
config = load_config()
|
||||
logger.debug(f"Loaded devices: {config['devices']}")
|
||||
return render_template('index.html', devices=config['devices'])
|
||||
|
||||
@app.route('/api/status')
|
||||
def status():
|
||||
return jsonify(device_status)
|
||||
|
||||
@app.route('/api/diagnostics')
|
||||
def get_diagnostics():
|
||||
config = load_config()
|
||||
@ -141,21 +163,10 @@ def get_diagnostics():
|
||||
for device in config['devices']:
|
||||
if device['device_id']:
|
||||
diagnostics[device['name']] = run_diagnostics(device)
|
||||
return jsonify(diagnostics)@app.route('/')
|
||||
def home():
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/api/status')
|
||||
def status():
|
||||
return jsonify(device_status)
|
||||
return jsonify(diagnostics)
|
||||
|
||||
# Application entry point
|
||||
if __name__ == '__main__':
|
||||
status_thread = threading.Thread(target=update_status, daemon=True)
|
||||
status_thread.start()
|
||||
app.run(debug=True)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def home():
|
||||
config = load_config()
|
||||
return render_template('index.html', devices=config['devices'])
|
||||
app.run(debug=True)
|
||||
12
index.html
12
index.html
@ -16,21 +16,23 @@
|
||||
<div class="metric-card">
|
||||
<h2>Network Overview</h2>
|
||||
<div id="network-health">
|
||||
{% for device in devices %}
|
||||
<div class="device-status" data-device-id="{{ device.device_id }}">
|
||||
{%- for device in devices %}
|
||||
<div class="device-status" data-device-name="{{ device.name }}">
|
||||
<span class="status-indicator"></span>
|
||||
<div class="device-info">
|
||||
<span class="device-name">{{ device.name }}</span>
|
||||
<span class="device-details">{{ device.ip }}</span>
|
||||
<span class="device-type">{{ device.type }} ({{ device.connection_type }})</span>
|
||||
{% if device.critical %}
|
||||
<span class="critical-badge">Critical</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{%- endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html></html>
|
||||
@ -1,3 +1,24 @@
|
||||
// Initialization
|
||||
const UPDATE_INTERVALS = {
|
||||
deviceStatus: 30000,
|
||||
diagnostics: 60000
|
||||
};
|
||||
|
||||
// Core update functions
|
||||
function updateDeviceStatus() {
|
||||
console.log('Updating device status...');
|
||||
fetch('/api/status')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log('Received status data:', data);
|
||||
Object.entries(data).forEach(([deviceName, status]) => {
|
||||
console.log(`Updating ${deviceName} status to ${status}`);
|
||||
updateDeviceIndicator(deviceName, status);
|
||||
});
|
||||
})
|
||||
.catch(error => console.error('Error updating status:', error));
|
||||
}
|
||||
|
||||
function updateDiagnostics() {
|
||||
fetch('/api/diagnostics')
|
||||
.then(response => response.json())
|
||||
@ -12,6 +33,7 @@ function updateDiagnostics() {
|
||||
});
|
||||
}
|
||||
|
||||
// Element creation functions
|
||||
function createDiagnosticElement(device, diagnostics) {
|
||||
const element = document.createElement('div');
|
||||
element.className = `diagnostic-item ${diagnostics.connection_type}-diagnostic`;
|
||||
@ -63,20 +85,16 @@ function createInterfaceHTML(interfaces) {
|
||||
return html;
|
||||
}
|
||||
|
||||
function updateDeviceStatus() {
|
||||
fetch('/api/status')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
Object.entries(data).forEach(([deviceName, status]) => {
|
||||
updateDeviceIndicator(deviceName, status);
|
||||
});
|
||||
});
|
||||
// Initialize updates
|
||||
function initializeUpdates() {
|
||||
// Set update intervals
|
||||
setInterval(updateDeviceStatus, UPDATE_INTERVALS.deviceStatus);
|
||||
setInterval(updateDiagnostics, UPDATE_INTERVALS.diagnostics);
|
||||
|
||||
// Initial updates
|
||||
updateDeviceStatus();
|
||||
updateDiagnostics();
|
||||
}
|
||||
|
||||
// Update intervals
|
||||
setInterval(updateDeviceStatus, 30000);
|
||||
setInterval(updateDiagnostics, 60000);
|
||||
|
||||
// Initial updates
|
||||
updateDeviceStatus();
|
||||
updateDiagnostics();
|
||||
// Start the application
|
||||
initializeUpdates();
|
||||
Reference in New Issue
Block a user