#!/usr/bin/env python3 """ WaouW Device Agent v2.0 COMPLETE Raspberry Pi monitoring agent avec surveillance complète de tous les services """ import os import sys import time import json import hmac import hashlib import uuid import signal import logging import subprocess import socket import requests from datetime import datetime from pathlib import Path from typing import Dict, List, Optional, Any import asyncio import aiohttp import psutil import docker # Configuration DEFAULT_CONFIG = { "api_url": "http://localhost:8000/api/v1", "heartbeat_interval": 30, "max_retries": 3, "retry_delay": 5, "timeout": 30, "log_level": "INFO", "device_id_file": "/etc/waouw/device_id", "config_file": "/etc/waouw/agent.conf", "log_file": "/var/log/waouw/agent.log", "enable_docker_monitoring": True, "enable_email_monitoring": True, "enable_security_monitoring": True, "enable_network_monitoring": True } # Services à surveiller MONITORED_SERVICES = { # Core services "traefik": {"type": "proxy", "port": 8080, "health_path": "/ping"}, "postgres": {"type": "database", "port": 5432}, "redis": {"type": "cache", "port": 6379}, "backend": {"type": "api", "port": 8000, "health_path": "/health"}, "frontend": {"type": "web", "port": 80}, # Email services "postfix": {"type": "email", "port": 587, "service": "postfix"}, "dovecot": {"type": "email", "port": 993, "service": "dovecot"}, "roundcube": {"type": "webmail", "port": 80, "health_path": "/"}, "mailadmin": {"type": "email_admin", "port": 80, "health_path": "/"}, # Cloud services "nextcloud": {"type": "cloud", "port": 80, "health_path": "/status.php"}, "nextcloud_db": {"type": "database", "port": 3306}, # Security services "fail2ban": {"type": "security", "service": "fail2ban"}, "openvpn": {"type": "vpn", "port": 1194, "service": "openvpn"}, # Monitoring services "graylog": {"type": "logging", "port": 9000, "health_path": "/api/system/lbstatus"}, "prometheus": {"type": "metrics", "port": 9090, "health_path": "/-/healthy"}, "grafana": {"type": "dashboard", "port": 3000, "health_path": "/api/health"}, # System services "webmin": {"type": "system", "port": 10000}, "phpmyadmin": {"type": "database_admin", "port": 80}, } class WaouwAgentComplete: """WaouW Device Agent avec surveillance complète""" def __init__(self, config_path: Optional[str] = None): """Initialize the agent""" self.config = self._load_config(config_path) self.device_id = self._get_device_id() self.session: Optional[aiohttp.ClientSession] = None self.running = False self.logger = self._setup_logging() # Docker client for container monitoring try: self.docker_client = docker.from_env() if self.config.get("enable_docker_monitoring") else None except Exception as e: self.logger.warning(f"Docker client not available: {e}") self.docker_client = None # Metrics cache self._last_network_stats = None self._last_disk_stats = None self._service_status_cache = {} # Setup signal handlers signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _load_config(self, config_path: Optional[str] = None) -> Dict[str, Any]: """Load configuration from file or environment""" config = DEFAULT_CONFIG.copy() # Load from file if exists if config_path and Path(config_path).exists(): try: with open(config_path, 'r') as f: file_config = json.load(f) config.update(file_config) except Exception as e: print(f"Error loading config file: {e}") # Override with environment variables for key in config: env_key = f"WAOUW_{key.upper()}" if env_key in os.environ: value = os.environ[env_key] # Convert to appropriate type if isinstance(config[key], bool): config[key] = value.lower() in ('true', '1', 'yes', 'on') elif isinstance(config[key], int): config[key] = int(value) else: config[key] = value return config def _setup_logging(self) -> logging.Logger: """Setup logging configuration""" logger = logging.getLogger("waouw_agent") logger.setLevel(getattr(logging, self.config["log_level"])) # Create log directory if it doesn't exist log_file = Path(self.config["log_file"]) log_file.parent.mkdir(parents=True, exist_ok=True) # File handler file_handler = logging.FileHandler(log_file) file_formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) file_handler.setFormatter(file_formatter) logger.addHandler(file_handler) # Console handler console_handler = logging.StreamHandler() console_formatter = logging.Formatter( '%(levelname)s - %(message)s' ) console_handler.setFormatter(console_formatter) logger.addHandler(console_handler) return logger def _get_device_id(self) -> str: """Get or generate device ID""" device_id_file = Path(self.config["device_id_file"]) if device_id_file.exists(): try: return device_id_file.read_text().strip() except Exception as e: self.logger.warning(f"Error reading device ID: {e}") # Generate new device ID device_id = str(uuid.uuid4()) try: device_id_file.parent.mkdir(parents=True, exist_ok=True) device_id_file.write_text(device_id) device_id_file.chmod(0o600) except Exception as e: self.logger.warning(f"Error saving device ID: {e}") return device_id def _signal_handler(self, signum, frame): """Handle shutdown signals""" self.logger.info(f"Received signal {signum}, shutting down...") self.running = False def collect_system_metrics(self) -> Dict[str, Any]: """Collect comprehensive system metrics""" metrics = {} try: # CPU metrics cpu_percent = psutil.cpu_percent(interval=1) cpu_count = psutil.cpu_count() load_avg = psutil.getloadavg() if hasattr(psutil, 'getloadavg') else [0, 0, 0] metrics["cpu"] = { "percent": cpu_percent, "count": cpu_count, "load_avg_1m": load_avg[0], "load_avg_5m": load_avg[1], "load_avg_15m": load_avg[2] } # Memory metrics memory = psutil.virtual_memory() swap = psutil.swap_memory() metrics["memory"] = { "total": memory.total, "available": memory.available, "percent": memory.percent, "used": memory.used, "free": memory.free, "swap_total": swap.total, "swap_used": swap.used, "swap_percent": swap.percent } # Disk metrics disk_usage = psutil.disk_usage('/') disk_io = psutil.disk_io_counters() metrics["disk"] = { "total": disk_usage.total, "used": disk_usage.used, "free": disk_usage.free, "percent": (disk_usage.used / disk_usage.total) * 100, "read_bytes": disk_io.read_bytes if disk_io else 0, "write_bytes": disk_io.write_bytes if disk_io else 0, "read_count": disk_io.read_count if disk_io else 0, "write_count": disk_io.write_count if disk_io else 0 } # Network metrics network_io = psutil.net_io_counters() network_connections = len(psutil.net_connections()) metrics["network"] = { "bytes_sent": network_io.bytes_sent, "bytes_recv": network_io.bytes_recv, "packets_sent": network_io.packets_sent, "packets_recv": network_io.packets_recv, "errin": network_io.errin, "errout": network_io.errout, "dropin": network_io.dropin, "dropout": network_io.dropout, "connections": network_connections } # Calculate deltas for rates if self._last_network_stats: time_delta = time.time() - self._last_network_stats["timestamp"] if time_delta > 0: metrics["network"]["bytes_sent_rate"] = ( network_io.bytes_sent - self._last_network_stats["bytes_sent"] ) / time_delta metrics["network"]["bytes_recv_rate"] = ( network_io.bytes_recv - self._last_network_stats["bytes_recv"] ) / time_delta self._last_network_stats = { "timestamp": time.time(), "bytes_sent": network_io.bytes_sent, "bytes_recv": network_io.bytes_recv } # Temperature (Raspberry Pi specific) try: with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f: temp_celsius = float(f.read().strip()) / 1000.0 metrics["temperature"] = {"celsius": temp_celsius} except (FileNotFoundError, ValueError): pass # Boot time and uptime boot_time = psutil.boot_time() metrics["uptime"] = { "boot_time": boot_time, "uptime_seconds": time.time() - boot_time } except Exception as e: self.logger.error(f"Error collecting system metrics: {e}") return metrics def collect_docker_services(self) -> Dict[str, Any]: """Collect Docker services status""" if not self.docker_client: return {} services = {} try: containers = self.docker_client.containers.list(all=True) for container in containers: if container.name.startswith('waouw_'): service_name = container.name.replace('waouw_', '') # Get container stats try: stats = container.stats(stream=False, decode=True) # Calculate CPU percentage cpu_delta = ( stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage'] ) system_delta = ( stats['cpu_stats']['system_cpu_usage'] - stats['precpu_stats']['system_cpu_usage'] ) cpu_percent = 0 if system_delta > 0: cpu_percent = (cpu_delta / system_delta) * len(stats['cpu_stats']['cpu_usage']['percpu_usage']) * 100 # Calculate memory usage memory_usage = stats['memory_stats'].get('usage', 0) memory_limit = stats['memory_stats'].get('limit', 0) memory_percent = (memory_usage / memory_limit * 100) if memory_limit > 0 else 0 services[service_name] = { "status": container.status, "health": getattr(container.attrs.get('State', {}), 'Health', {}).get('Status', 'unknown'), "created": container.attrs['Created'], "started_at": container.attrs['State'].get('StartedAt'), "cpu_percent": round(cpu_percent, 2), "memory_usage_mb": round(memory_usage / 1024 / 1024, 2), "memory_percent": round(memory_percent, 2), "restart_count": container.attrs['RestartCount'], "image": container.image.tags[0] if container.image.tags else "unknown" } except Exception as e: # Fallback for containers without stats services[service_name] = { "status": container.status, "health": "unknown", "created": container.attrs['Created'], "started_at": container.attrs['State'].get('StartedAt'), "restart_count": container.attrs['RestartCount'], "image": container.image.tags[0] if container.image.tags else "unknown", "error": str(e) } except Exception as e: self.logger.error(f"Error collecting Docker services: {e}") return services def collect_email_metrics(self) -> Dict[str, Any]: """Collect email services metrics""" if not self.config.get("enable_email_monitoring"): return {} email_metrics = {} try: # Check Postfix status postfix_status = self._check_systemd_service("postfix") email_metrics["postfix"] = postfix_status # Check Dovecot status dovecot_status = self._check_systemd_service("dovecot") email_metrics["dovecot"] = dovecot_status # Check mail queue try: result = subprocess.run( ["mailq"], capture_output=True, text=True, timeout=10 ) queue_size = 0 if result.returncode == 0: lines = result.stdout.strip().split('\n') if lines and "Mail queue is empty" not in lines[-1]: # Parse queue size from output for line in lines: if "requests" in line: queue_size = int(line.split()[0]) break email_metrics["mail_queue_size"] = queue_size except Exception as e: self.logger.warning(f"Error checking mail queue: {e}") email_metrics["mail_queue_size"] = -1 # Check mail logs for errors try: result = subprocess.run( ["grep", "-c", "error\\|Error\\|ERROR", "/var/log/mail.log"], capture_output=True, text=True, timeout=5 ) error_count = int(result.stdout.strip()) if result.returncode == 0 else 0 email_metrics["mail_errors_today"] = error_count except Exception: email_metrics["mail_errors_today"] = -1 except Exception as e: self.logger.error(f"Error collecting email metrics: {e}") return email_metrics def collect_security_metrics(self) -> Dict[str, Any]: """Collect security metrics""" if not self.config.get("enable_security_monitoring"): return {} security_metrics = {} try: # Fail2Ban status fail2ban_status = self._check_systemd_service("fail2ban") security_metrics["fail2ban"] = fail2ban_status # Get banned IPs count try: result = subprocess.run( ["fail2ban-client", "status"], capture_output=True, text=True, timeout=10 ) if result.returncode == 0: # Parse jails jails = [] for line in result.stdout.split('\n'): if "Jail list:" in line: jails_str = line.split("Jail list:")[1].strip() jails = [j.strip() for j in jails_str.split(',') if j.strip()] total_banned = 0 jail_stats = {} for jail in jails: try: jail_result = subprocess.run( ["fail2ban-client", "status", jail], capture_output=True, text=True, timeout=5 ) if jail_result.returncode == 0: banned_count = 0 for line in jail_result.stdout.split('\n'): if "Currently banned:" in line: banned_count = int(line.split(":")[1].strip()) break jail_stats[jail] = banned_count total_banned += banned_count except Exception: jail_stats[jail] = -1 security_metrics["banned_ips_total"] = total_banned security_metrics["jails"] = jail_stats except Exception as e: self.logger.warning(f"Error checking Fail2Ban status: {e}") security_metrics["banned_ips_total"] = -1 # UFW firewall status try: result = subprocess.run( ["ufw", "status"], capture_output=True, text=True, timeout=5 ) if result.returncode == 0: status = "active" if "Status: active" in result.stdout else "inactive" security_metrics["firewall_status"] = status else: security_metrics["firewall_status"] = "unknown" except Exception: security_metrics["firewall_status"] = "unknown" # OpenVPN status openvpn_status = self._check_systemd_service("openvpn") security_metrics["openvpn"] = openvpn_status # Check for recent auth failures try: result = subprocess.run( ["grep", "-c", "authentication failure", "/var/log/auth.log"], capture_output=True, text=True, timeout=5 ) auth_failures = int(result.stdout.strip()) if result.returncode == 0 else 0 security_metrics["auth_failures_today"] = auth_failures except Exception: security_metrics["auth_failures_today"] = -1 except Exception as e: self.logger.error(f"Error collecting security metrics: {e}") return security_metrics def collect_network_status(self) -> Dict[str, Any]: """Collect network connectivity status""" if not self.config.get("enable_network_monitoring"): return {} network_status = {} try: # Check internet connectivity try: response = requests.get("https://8.8.8.8", timeout=5) network_status["internet"] = True except Exception: network_status["internet"] = False # Check DNS resolution try: socket.gethostbyname("google.com") network_status["dns"] = True except Exception: network_status["dns"] = False # Get network interfaces interfaces = {} for interface_name, interface_addresses in psutil.net_if_addrs().items(): if interface_name != 'lo': # Skip loopback for address in interface_addresses: if address.family == socket.AF_INET: interfaces[interface_name] = { "ip": address.address, "netmask": address.netmask, "broadcast": address.broadcast } break network_status["interfaces"] = interfaces # Check if services are accessible locally service_checks = {} for service_name, service_config in MONITORED_SERVICES.items(): if "port" in service_config: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2) result = sock.connect_ex(('localhost', service_config["port"])) service_checks[service_name] = result == 0 sock.close() except Exception: service_checks[service_name] = False network_status["service_ports"] = service_checks except Exception as e: self.logger.error(f"Error collecting network status: {e}") return network_status def _check_systemd_service(self, service_name: str) -> Dict[str, Any]: """Check systemd service status""" try: result = subprocess.run( ["systemctl", "is-active", service_name], capture_output=True, text=True, timeout=5 ) is_active = result.stdout.strip() == "active" result = subprocess.run( ["systemctl", "is-enabled", service_name], capture_output=True, text=True, timeout=5 ) is_enabled = result.stdout.strip() == "enabled" return { "active": is_active, "enabled": is_enabled, "status": "running" if is_active else "stopped" } except Exception as e: return { "active": False, "enabled": False, "status": "unknown", "error": str(e) } def _check_service_health(self, service_name: str, service_config: Dict[str, Any]) -> Dict[str, Any]: """Check service health via HTTP health check""" if "health_path" not in service_config: return {"healthy": None, "reason": "No health check configured"} try: port = service_config.get("port", 80) health_path = service_config["health_path"] url = f"http://localhost:{port}{health_path}" response = requests.get(url, timeout=5) healthy = response.status_code == 200 return { "healthy": healthy, "status_code": response.status_code, "response_time_ms": response.elapsed.total_seconds() * 1000 } except Exception as e: return { "healthy": False, "error": str(e) } def create_heartbeat_payload(self) -> Dict[str, Any]: """Create comprehensive heartbeat payload""" timestamp = datetime.utcnow().isoformat() payload = { "device_id": self.device_id, "timestamp": timestamp, "agent_version": "2.0.0-complete", "system_metrics": self.collect_system_metrics(), "docker_services": self.collect_docker_services(), "email_metrics": self.collect_email_metrics(), "security_metrics": self.collect_security_metrics(), "network_status": self.collect_network_status() } # Add service health checks service_health = {} for service_name, service_config in MONITORED_SERVICES.items(): health = self._check_service_health(service_name, service_config) service_health[service_name] = health payload["service_health"] = service_health return payload def _sign_payload(self, payload: Dict[str, Any]) -> str: """Sign payload with HMAC""" secret = os.getenv("DEVICE_HMAC_SECRET", "default_secret") message = json.dumps(payload, sort_keys=True).encode() signature = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest() return signature async def send_heartbeat(self) -> bool: """Send heartbeat to API""" try: payload = self.create_heartbeat_payload() signature = self._sign_payload(payload) headers = { "Content-Type": "application/json", "X-Signature": signature, "User-Agent": f"WaouW-Agent/2.0-complete" } url = f"{self.config['api_url']}/devices/heartbeat" async with self.session.post(url, json=payload, headers=headers) as response: if response.status == 200: result = await response.json() self.logger.debug(f"Heartbeat sent successfully: {result}") # Handle any commands from server if "commands" in result: await self._handle_commands(result["commands"]) return True else: error_text = await response.text() self.logger.error(f"Heartbeat failed: {response.status} - {error_text}") return False except Exception as e: self.logger.error(f"Error sending heartbeat: {e}") return False async def _handle_commands(self, commands: List[Dict[str, Any]]): """Handle commands from server""" for command in commands: try: cmd_type = command.get("type") cmd_params = command.get("params", {}) self.logger.info(f"Executing command: {cmd_type}") if cmd_type == "restart_service": service_name = cmd_params.get("service") if service_name in MONITORED_SERVICES: await self._restart_service(service_name) elif cmd_type == "update_config": new_config = cmd_params.get("config", {}) self.config.update(new_config) elif cmd_type == "collect_logs": log_lines = cmd_params.get("lines", 100) await self._send_logs(log_lines) else: self.logger.warning(f"Unknown command type: {cmd_type}") except Exception as e: self.logger.error(f"Error executing command {command}: {e}") async def _restart_service(self, service_name: str): """Restart a service""" try: if self.docker_client: container_name = f"waouw_{service_name}" try: container = self.docker_client.containers.get(container_name) container.restart() self.logger.info(f"Restarted Docker container: {container_name}") return except docker.errors.NotFound: pass # Try systemd service result = subprocess.run( ["sudo", "systemctl", "restart", service_name], capture_output=True, text=True, timeout=30 ) if result.returncode == 0: self.logger.info(f"Restarted systemd service: {service_name}") else: self.logger.error(f"Failed to restart service {service_name}: {result.stderr}") except Exception as e: self.logger.error(f"Error restarting service {service_name}: {e}") async def _send_logs(self, lines: int): """Send recent logs to server""" try: # Collect logs from various sources logs = {} # System logs result = subprocess.run( ["journalctl", "--lines", str(lines), "--output", "json"], capture_output=True, text=True, timeout=10 ) if result.returncode == 0: logs["system"] = result.stdout # WaouW logs log_file = Path(self.config["log_file"]) if log_file.exists(): with open(log_file, 'r') as f: log_lines = f.readlines() logs["agent"] = ''.join(log_lines[-lines:]) # Send logs to API payload = { "device_id": self.device_id, "timestamp": datetime.utcnow().isoformat(), "logs": logs } url = f"{self.config['api_url']}/devices/logs" async with self.session.post(url, json=payload) as response: if response.status == 200: self.logger.info("Logs sent successfully") else: self.logger.error(f"Failed to send logs: {response.status}") except Exception as e: self.logger.error(f"Error sending logs: {e}") async def run(self): """Main agent loop""" self.logger.info("Starting WaouW Agent v2.0 COMPLETE") self.running = True # Create HTTP session connector = aiohttp.TCPConnector(limit=10) timeout = aiohttp.ClientTimeout(total=self.config["timeout"]) self.session = aiohttp.ClientSession(connector=connector, timeout=timeout) try: while self.running: success = await self.send_heartbeat() if success: self.logger.debug("Heartbeat cycle completed successfully") else: self.logger.warning("Heartbeat cycle failed") # Wait for next heartbeat await asyncio.sleep(self.config["heartbeat_interval"]) except Exception as e: self.logger.error(f"Agent error: {e}") finally: if self.session: await self.session.close() self.logger.info("WaouW Agent stopped") async def main(): """Main entry point""" import argparse parser = argparse.ArgumentParser(description="WaouW Device Agent v2.0 COMPLETE") parser.add_argument("--config", help="Configuration file path") parser.add_argument("--daemon", action="store_true", help="Run as daemon") parser.add_argument("--test", action="store_true", help="Test mode - single heartbeat") args = parser.parse_args() # Create agent agent = WaouwAgentComplete(args.config) if args.test: # Test mode - single heartbeat agent.logger.info("Running in test mode") connector = aiohttp.TCPConnector(limit=10) timeout = aiohttp.ClientTimeout(total=agent.config["timeout"]) agent.session = aiohttp.ClientSession(connector=connector, timeout=timeout) try: payload = agent.create_heartbeat_payload() print("Test payload created:") print(json.dumps(payload, indent=2)) success = await agent.send_heartbeat() print(f"Heartbeat test: {'SUCCESS' if success else 'FAILED'}") finally: await agent.session.close() else: # Normal operation if args.daemon: # TODO: Implement proper daemonization pass await agent.run() if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print("\nShutdown requested by user") except Exception as e: print(f"Fatal error: {e}") sys.exit(1)