| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595 |
- #!/usr/bin/env python3
- """
- WaouW Device Agent v2.0
- Raspberry Pi monitoring agent with heartbeat and metrics collection
- """
- import os
- import sys
- import time
- import json
- import hmac
- import hashlib
- import uuid
- import signal
- import logging
- import subprocess
- from datetime import datetime
- from pathlib import Path
- from typing import Dict, List, Optional, Any
- import asyncio
- import aiohttp
- import psutil
- # 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"
- }
- class WaouwAgent:
- """WaouW Device Agent main class"""
-
- 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()
-
- # Metrics cache
- self._last_network_stats = None
- self._boot_time = psutil.boot_time()
-
- # 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 and environment"""
- config = DEFAULT_CONFIG.copy()
-
- # Load from config file
- 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"Warning: Failed to load config file {config_path}: {e}")
-
- # Override with environment variables
- env_mapping = {
- "WAOUW_API_URL": "api_url",
- "WAOUW_HEARTBEAT_INTERVAL": "heartbeat_interval",
- "WAOUW_HMAC_SECRET": "hmac_secret",
- "WAOUW_DEVICE_ID": "device_id",
- "WAOUW_LOG_LEVEL": "log_level"
- }
-
- for env_var, config_key in env_mapping.items():
- if env_var in os.environ:
- value = os.environ[env_var]
- # Convert numeric values
- if config_key in ["heartbeat_interval", "max_retries", "retry_delay", "timeout"]:
- try:
- value = int(value)
- except ValueError:
- pass
- config[config_key] = value
-
- return config
-
- def _get_device_id(self) -> str:
- """Get or generate stable device ID"""
- device_id_file = Path(self.config["device_id_file"])
-
- # Check if device ID already exists
- if device_id_file.exists():
- try:
- device_id = device_id_file.read_text().strip()
- if device_id and len(device_id) == 36: # Valid UUID length
- return device_id
- except Exception:
- pass
-
- # Generate new device ID
- try:
- # Use machine-id if available
- machine_id_file = Path("/etc/machine-id")
- if machine_id_file.exists():
- machine_id = machine_id_file.read_text().strip()
- else:
- machine_id = str(uuid.getnode())
-
- # Create namespace UUID based on machine characteristics
- mac_address = ':'.join([f'{byte:02x}' for byte in uuid.getnode().to_bytes(6, 'big')])
- hostname = os.uname().nodename
- namespace_data = f"{machine_id}-{mac_address}-{hostname}"
- device_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, namespace_data)
- device_id = str(device_uuid)
-
- # Save device ID
- device_id_file.parent.mkdir(parents=True, exist_ok=True)
- device_id_file.write_text(device_id)
- device_id_file.chmod(0o600)
-
- return device_id
-
- except Exception as e:
- # Fallback to random UUID
- device_id = str(uuid.uuid4())
- print(f"Warning: Failed to create stable device ID, using random: {e}")
- return device_id
-
- 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
- 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_handler.setLevel(logging.DEBUG)
-
- # Console handler
- console_handler = logging.StreamHandler()
- console_handler.setLevel(logging.INFO)
-
- # Formatter
- formatter = logging.Formatter(
- '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
- )
- file_handler.setFormatter(formatter)
- console_handler.setFormatter(formatter)
-
- logger.addHandler(file_handler)
- logger.addHandler(console_handler)
-
- return logger
-
- 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"""
- try:
- # CPU metrics
- cpu_percent = psutil.cpu_percent(interval=1)
- cpu_count = psutil.cpu_count()
- try:
- load_avg = os.getloadavg()
- except (OSError, AttributeError):
- # Windows doesn't have getloadavg
- load_avg = (0.0, 0.0, 0.0)
-
- # Memory metrics
- memory = psutil.virtual_memory()
- swap = psutil.swap_memory()
-
- # Disk metrics
- disk = psutil.disk_usage('/')
-
- # Network metrics
- network = psutil.net_io_counters()
- network_delta = None
- if self._last_network_stats:
- network_delta = {
- 'bytes_sent': network.bytes_sent - self._last_network_stats.bytes_sent,
- 'bytes_recv': network.bytes_recv - self._last_network_stats.bytes_recv
- }
- self._last_network_stats = network
-
- # Temperature (Raspberry Pi specific)
- temperature = self._get_cpu_temperature()
-
- # System uptime
- uptime = time.time() - self._boot_time
-
- # Docker metrics
- docker_metrics = self._get_docker_metrics()
-
- # Service status
- services_status = self._check_services()
-
- return {
- 'device_id': self.device_id,
- 'timestamp': int(time.time()),
- 'hostname': os.uname().nodename,
-
- # CPU
- 'cpu_percent': cpu_percent,
- 'cpu_count': cpu_count,
- 'load_average_1m': load_avg[0],
- 'load_average_5m': load_avg[1],
- 'load_average_15m': load_avg[2],
-
- # Memory (MB)
- 'memory_total': memory.total // (1024 * 1024),
- 'memory_available': memory.available // (1024 * 1024),
- 'memory_used': memory.used // (1024 * 1024),
- 'memory_percent': memory.percent,
-
- # Swap (MB)
- 'swap_total': swap.total // (1024 * 1024),
- 'swap_used': swap.used // (1024 * 1024),
- 'swap_percent': swap.percent,
-
- # Disk (GB)
- 'disk_total': disk.total / (1024 ** 3),
- 'disk_used': disk.used / (1024 ** 3),
- 'disk_free': disk.free / (1024 ** 3),
- 'disk_percent': (disk.used / disk.total) * 100,
-
- # Network
- 'network_bytes_sent': network.bytes_sent,
- 'network_bytes_recv': network.bytes_recv,
- 'network_delta': network_delta,
-
- # System
- 'temperature': temperature,
- 'uptime': uptime,
-
- # Docker
- **docker_metrics,
-
- # Services
- 'services_status': services_status,
-
- # Agent info
- 'agent_version': '2.0.0',
- }
-
- except Exception as e:
- self.logger.error(f"Failed to collect metrics: {e}")
- return {
- 'device_id': self.device_id,
- 'timestamp': int(time.time()),
- 'error': str(e)
- }
-
- def _get_cpu_temperature(self) -> Optional[float]:
- """Get CPU temperature (Raspberry Pi specific)"""
- try:
- # Try Raspberry Pi thermal zone
- temp_file = Path("/sys/class/thermal/thermal_zone0/temp")
- if temp_file.exists():
- temp_millidegrees = int(temp_file.read_text().strip())
- return temp_millidegrees / 1000.0
-
- # Try other methods
- try:
- result = subprocess.run(
- ["vcgencmd", "measure_temp"],
- capture_output=True,
- text=True,
- timeout=5
- )
- if result.returncode == 0:
- # Parse output like "temp=42.8'C"
- temp_str = result.stdout.strip()
- if "temp=" in temp_str:
- temp_value = temp_str.split("=")[1].split("'")[0]
- return float(temp_value)
- except Exception:
- pass
-
- return None
-
- except Exception:
- return None
-
- def _get_docker_metrics(self) -> Dict[str, Any]:
- """Get Docker metrics"""
- try:
- # Get container count
- result = subprocess.run(
- ["docker", "ps", "-q"],
- capture_output=True,
- text=True,
- timeout=10
- )
-
- if result.returncode == 0:
- running_containers = len([line for line in result.stdout.strip().split('\n') if line])
- else:
- running_containers = None
-
- # Get total containers
- result = subprocess.run(
- ["docker", "ps", "-aq"],
- capture_output=True,
- text=True,
- timeout=10
- )
-
- if result.returncode == 0:
- total_containers = len([line for line in result.stdout.strip().split('\n') if line])
- else:
- total_containers = None
-
- # Get image count
- result = subprocess.run(
- ["docker", "images", "-q"],
- capture_output=True,
- text=True,
- timeout=10
- )
-
- if result.returncode == 0:
- image_count = len([line for line in result.stdout.strip().split('\n') if line])
- else:
- image_count = None
-
- return {
- 'docker_containers_running': running_containers,
- 'docker_containers_total': total_containers,
- 'docker_images_count': image_count
- }
-
- except Exception as e:
- self.logger.warning(f"Failed to get Docker metrics: {e}")
- return {
- 'docker_containers_running': None,
- 'docker_containers_total': None,
- 'docker_images_count': None
- }
-
- def _check_services(self) -> Dict[str, bool]:
- """Check status of critical services"""
- services = ['docker', 'traefik', 'sshd']
- status = {}
-
- for service in services:
- try:
- result = subprocess.run(
- ['systemctl', 'is-active', service],
- capture_output=True,
- text=True,
- timeout=5
- )
- status[service] = result.stdout.strip() == 'active'
- except Exception:
- status[service] = False
-
- return status
-
- def _create_signature(self, payload: Dict[str, Any]) -> str:
- """Create HMAC signature for payload"""
- hmac_secret = self.config.get('hmac_secret')
- if not hmac_secret:
- raise ValueError("HMAC secret not configured")
-
- message = json.dumps(payload, sort_keys=True).encode()
- signature = hmac.new(
- hmac_secret.encode(),
- message,
- hashlib.sha256
- ).hexdigest()
-
- return signature
-
- async def send_heartbeat(self) -> bool:
- """Send heartbeat with metrics to API"""
- try:
- metrics = self.collect_system_metrics()
- signature = self._create_signature(metrics)
-
- headers = {
- 'Content-Type': 'application/json',
- 'X-Device-Signature': signature,
- 'User-Agent': f'WaouwAgent/2.0.0 ({os.uname().sysname})'
- }
-
- url = f"{self.config['api_url']}/devices/heartbeat"
-
- async with self.session.post(
- url,
- json=metrics,
- headers=headers,
- timeout=aiohttp.ClientTimeout(total=self.config['timeout'])
- ) as response:
-
- if response.status == 200:
- result = await response.json()
- self.logger.debug(f"Heartbeat sent successfully: {response.status}")
-
- # Handle any commands from server
- commands = result.get('commands', [])
- if commands:
- await self._handle_commands(commands)
-
- return True
- else:
- error_text = await response.text()
- self.logger.warning(
- f"Heartbeat failed: HTTP {response.status} - {error_text}"
- )
- return False
-
- except asyncio.TimeoutError:
- self.logger.warning("Heartbeat timeout")
- return False
- except Exception as e:
- self.logger.error(f"Heartbeat error: {e}")
- return False
-
- async def _handle_commands(self, commands: List[Dict[str, Any]]):
- """Handle commands received from server"""
- for command in commands:
- try:
- cmd_type = command.get('type')
- cmd_data = command.get('data', {})
-
- self.logger.info(f"Executing command: {cmd_type}")
-
- if cmd_type == 'ping':
- self.logger.info("Ping command received")
-
- elif cmd_type == 'restart_service':
- service = cmd_data.get('service')
- if service in ['docker', 'traefik']:
- await self._restart_service(service)
-
- elif cmd_type == 'update_config':
- await self._update_config(cmd_data)
-
- else:
- self.logger.warning(f"Unknown command type: {cmd_type}")
-
- except Exception as e:
- self.logger.error(f"Command execution failed: {e}")
-
- async def _restart_service(self, service_name: str):
- """Restart a system service"""
- try:
- process = await asyncio.create_subprocess_exec(
- 'sudo', 'systemctl', 'restart', service_name,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE
- )
-
- stdout, stderr = await process.communicate()
-
- if process.returncode == 0:
- self.logger.info(f"Service {service_name} restarted successfully")
- else:
- self.logger.error(
- f"Failed to restart {service_name}: {stderr.decode()}"
- )
-
- except Exception as e:
- self.logger.error(f"Error restarting service {service_name}: {e}")
-
- async def _update_config(self, new_config: Dict[str, Any]):
- """Update agent configuration"""
- try:
- # Only allow safe configuration updates
- allowed_keys = ['heartbeat_interval', 'log_level']
-
- for key, value in new_config.items():
- if key in allowed_keys:
- self.config[key] = value
- self.logger.info(f"Updated config: {key} = {value}")
-
- # Apply log level change immediately
- if 'log_level' in new_config:
- self.logger.setLevel(getattr(logging, new_config['log_level']))
-
- except Exception as e:
- self.logger.error(f"Failed to update config: {e}")
-
- async def run(self):
- """Main agent loop"""
- self.logger.info(f"Starting WaouW Agent v2.0.0 (Device ID: {self.device_id})")
- self.running = True
-
- # Create HTTP session
- connector = aiohttp.TCPConnector(limit=10, limit_per_host=5)
- self.session = aiohttp.ClientSession(connector=connector)
-
- retry_count = 0
-
- try:
- while self.running:
- success = await self.send_heartbeat()
-
- if success:
- retry_count = 0
- await asyncio.sleep(self.config['heartbeat_interval'])
- else:
- retry_count += 1
- if retry_count <= self.config['max_retries']:
- delay = self.config['retry_delay'] * retry_count
- self.logger.info(f"Retrying in {delay} seconds (attempt {retry_count})")
- await asyncio.sleep(delay)
- else:
- self.logger.warning("Max retries exceeded, continuing with normal interval")
- retry_count = 0
- await asyncio.sleep(self.config['heartbeat_interval'])
-
- except KeyboardInterrupt:
- self.logger.info("Received keyboard interrupt")
- finally:
- if self.session:
- await self.session.close()
- self.logger.info("WaouW Agent stopped")
- def main():
- """Main entry point"""
- import argparse
-
- parser = argparse.ArgumentParser(description="WaouW Device Agent v2.0")
- parser.add_argument(
- '--config', '-c',
- help='Configuration file path',
- default=DEFAULT_CONFIG['config_file']
- )
- parser.add_argument(
- '--daemon', '-d',
- action='store_true',
- help='Run as daemon'
- )
- parser.add_argument(
- '--test',
- action='store_true',
- help='Test mode - send one heartbeat and exit'
- )
-
- args = parser.parse_args()
-
- # Create agent
- agent = WaouwAgent(args.config)
-
- if args.test:
- # Test mode
- async def test_heartbeat():
- connector = aiohttp.TCPConnector()
- agent.session = aiohttp.ClientSession(connector=connector)
- try:
- success = await agent.send_heartbeat()
- print(f"Heartbeat test: {'SUCCESS' if success else 'FAILED'}")
- return 0 if success else 1
- finally:
- await agent.session.close()
-
- exit_code = asyncio.run(test_heartbeat())
- sys.exit(exit_code)
-
- # Normal mode
- try:
- asyncio.run(agent.run())
- except KeyboardInterrupt:
- pass
- except Exception as e:
- print(f"Fatal error: {e}")
- sys.exit(1)
- if __name__ == "__main__":
- main()
|