1
0

waouw_agent.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. #!/usr/bin/env python3
  2. """
  3. WaouW Device Agent v2.0
  4. Raspberry Pi monitoring agent with heartbeat and metrics collection
  5. """
  6. import os
  7. import sys
  8. import time
  9. import json
  10. import hmac
  11. import hashlib
  12. import uuid
  13. import signal
  14. import logging
  15. import subprocess
  16. from datetime import datetime
  17. from pathlib import Path
  18. from typing import Dict, List, Optional, Any
  19. import asyncio
  20. import aiohttp
  21. import psutil
  22. # Configuration
  23. DEFAULT_CONFIG = {
  24. "api_url": "http://localhost:8000/api/v1",
  25. "heartbeat_interval": 30,
  26. "max_retries": 3,
  27. "retry_delay": 5,
  28. "timeout": 30,
  29. "log_level": "INFO",
  30. "device_id_file": "/etc/waouw/device_id",
  31. "config_file": "/etc/waouw/agent.conf",
  32. "log_file": "/var/log/waouw/agent.log"
  33. }
  34. class WaouwAgent:
  35. """WaouW Device Agent main class"""
  36. def __init__(self, config_path: Optional[str] = None):
  37. """Initialize the agent"""
  38. self.config = self._load_config(config_path)
  39. self.device_id = self._get_device_id()
  40. self.session: Optional[aiohttp.ClientSession] = None
  41. self.running = False
  42. self.logger = self._setup_logging()
  43. # Metrics cache
  44. self._last_network_stats = None
  45. self._boot_time = psutil.boot_time()
  46. # Signal handlers
  47. signal.signal(signal.SIGTERM, self._signal_handler)
  48. signal.signal(signal.SIGINT, self._signal_handler)
  49. def _load_config(self, config_path: Optional[str] = None) -> Dict[str, Any]:
  50. """Load configuration from file and environment"""
  51. config = DEFAULT_CONFIG.copy()
  52. # Load from config file
  53. if config_path and Path(config_path).exists():
  54. try:
  55. with open(config_path, 'r') as f:
  56. file_config = json.load(f)
  57. config.update(file_config)
  58. except Exception as e:
  59. print(f"Warning: Failed to load config file {config_path}: {e}")
  60. # Override with environment variables
  61. env_mapping = {
  62. "WAOUW_API_URL": "api_url",
  63. "WAOUW_HEARTBEAT_INTERVAL": "heartbeat_interval",
  64. "WAOUW_HMAC_SECRET": "hmac_secret",
  65. "WAOUW_DEVICE_ID": "device_id",
  66. "WAOUW_LOG_LEVEL": "log_level"
  67. }
  68. for env_var, config_key in env_mapping.items():
  69. if env_var in os.environ:
  70. value = os.environ[env_var]
  71. # Convert numeric values
  72. if config_key in ["heartbeat_interval", "max_retries", "retry_delay", "timeout"]:
  73. try:
  74. value = int(value)
  75. except ValueError:
  76. pass
  77. config[config_key] = value
  78. return config
  79. def _get_device_id(self) -> str:
  80. """Get or generate stable device ID"""
  81. device_id_file = Path(self.config["device_id_file"])
  82. # Check if device ID already exists
  83. if device_id_file.exists():
  84. try:
  85. device_id = device_id_file.read_text().strip()
  86. if device_id and len(device_id) == 36: # Valid UUID length
  87. return device_id
  88. except Exception:
  89. pass
  90. # Generate new device ID
  91. try:
  92. # Use machine-id if available
  93. machine_id_file = Path("/etc/machine-id")
  94. if machine_id_file.exists():
  95. machine_id = machine_id_file.read_text().strip()
  96. else:
  97. machine_id = str(uuid.getnode())
  98. # Create namespace UUID based on machine characteristics
  99. mac_address = ':'.join([f'{byte:02x}' for byte in uuid.getnode().to_bytes(6, 'big')])
  100. hostname = os.uname().nodename
  101. namespace_data = f"{machine_id}-{mac_address}-{hostname}"
  102. device_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, namespace_data)
  103. device_id = str(device_uuid)
  104. # Save device ID
  105. device_id_file.parent.mkdir(parents=True, exist_ok=True)
  106. device_id_file.write_text(device_id)
  107. device_id_file.chmod(0o600)
  108. return device_id
  109. except Exception as e:
  110. # Fallback to random UUID
  111. device_id = str(uuid.uuid4())
  112. print(f"Warning: Failed to create stable device ID, using random: {e}")
  113. return device_id
  114. def _setup_logging(self) -> logging.Logger:
  115. """Setup logging configuration"""
  116. logger = logging.getLogger("waouw-agent")
  117. logger.setLevel(getattr(logging, self.config["log_level"]))
  118. # Create log directory
  119. log_file = Path(self.config["log_file"])
  120. log_file.parent.mkdir(parents=True, exist_ok=True)
  121. # File handler
  122. file_handler = logging.FileHandler(log_file)
  123. file_handler.setLevel(logging.DEBUG)
  124. # Console handler
  125. console_handler = logging.StreamHandler()
  126. console_handler.setLevel(logging.INFO)
  127. # Formatter
  128. formatter = logging.Formatter(
  129. '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  130. )
  131. file_handler.setFormatter(formatter)
  132. console_handler.setFormatter(formatter)
  133. logger.addHandler(file_handler)
  134. logger.addHandler(console_handler)
  135. return logger
  136. def _signal_handler(self, signum, frame):
  137. """Handle shutdown signals"""
  138. self.logger.info(f"Received signal {signum}, shutting down...")
  139. self.running = False
  140. def collect_system_metrics(self) -> Dict[str, Any]:
  141. """Collect comprehensive system metrics"""
  142. try:
  143. # CPU metrics
  144. cpu_percent = psutil.cpu_percent(interval=1)
  145. cpu_count = psutil.cpu_count()
  146. try:
  147. load_avg = os.getloadavg()
  148. except (OSError, AttributeError):
  149. # Windows doesn't have getloadavg
  150. load_avg = (0.0, 0.0, 0.0)
  151. # Memory metrics
  152. memory = psutil.virtual_memory()
  153. swap = psutil.swap_memory()
  154. # Disk metrics
  155. disk = psutil.disk_usage('/')
  156. # Network metrics
  157. network = psutil.net_io_counters()
  158. network_delta = None
  159. if self._last_network_stats:
  160. network_delta = {
  161. 'bytes_sent': network.bytes_sent - self._last_network_stats.bytes_sent,
  162. 'bytes_recv': network.bytes_recv - self._last_network_stats.bytes_recv
  163. }
  164. self._last_network_stats = network
  165. # Temperature (Raspberry Pi specific)
  166. temperature = self._get_cpu_temperature()
  167. # System uptime
  168. uptime = time.time() - self._boot_time
  169. # Docker metrics
  170. docker_metrics = self._get_docker_metrics()
  171. # Service status
  172. services_status = self._check_services()
  173. return {
  174. 'device_id': self.device_id,
  175. 'timestamp': int(time.time()),
  176. 'hostname': os.uname().nodename,
  177. # CPU
  178. 'cpu_percent': cpu_percent,
  179. 'cpu_count': cpu_count,
  180. 'load_average_1m': load_avg[0],
  181. 'load_average_5m': load_avg[1],
  182. 'load_average_15m': load_avg[2],
  183. # Memory (MB)
  184. 'memory_total': memory.total // (1024 * 1024),
  185. 'memory_available': memory.available // (1024 * 1024),
  186. 'memory_used': memory.used // (1024 * 1024),
  187. 'memory_percent': memory.percent,
  188. # Swap (MB)
  189. 'swap_total': swap.total // (1024 * 1024),
  190. 'swap_used': swap.used // (1024 * 1024),
  191. 'swap_percent': swap.percent,
  192. # Disk (GB)
  193. 'disk_total': disk.total / (1024 ** 3),
  194. 'disk_used': disk.used / (1024 ** 3),
  195. 'disk_free': disk.free / (1024 ** 3),
  196. 'disk_percent': (disk.used / disk.total) * 100,
  197. # Network
  198. 'network_bytes_sent': network.bytes_sent,
  199. 'network_bytes_recv': network.bytes_recv,
  200. 'network_delta': network_delta,
  201. # System
  202. 'temperature': temperature,
  203. 'uptime': uptime,
  204. # Docker
  205. **docker_metrics,
  206. # Services
  207. 'services_status': services_status,
  208. # Agent info
  209. 'agent_version': '2.0.0',
  210. }
  211. except Exception as e:
  212. self.logger.error(f"Failed to collect metrics: {e}")
  213. return {
  214. 'device_id': self.device_id,
  215. 'timestamp': int(time.time()),
  216. 'error': str(e)
  217. }
  218. def _get_cpu_temperature(self) -> Optional[float]:
  219. """Get CPU temperature (Raspberry Pi specific)"""
  220. try:
  221. # Try Raspberry Pi thermal zone
  222. temp_file = Path("/sys/class/thermal/thermal_zone0/temp")
  223. if temp_file.exists():
  224. temp_millidegrees = int(temp_file.read_text().strip())
  225. return temp_millidegrees / 1000.0
  226. # Try other methods
  227. try:
  228. result = subprocess.run(
  229. ["vcgencmd", "measure_temp"],
  230. capture_output=True,
  231. text=True,
  232. timeout=5
  233. )
  234. if result.returncode == 0:
  235. # Parse output like "temp=42.8'C"
  236. temp_str = result.stdout.strip()
  237. if "temp=" in temp_str:
  238. temp_value = temp_str.split("=")[1].split("'")[0]
  239. return float(temp_value)
  240. except Exception:
  241. pass
  242. return None
  243. except Exception:
  244. return None
  245. def _get_docker_metrics(self) -> Dict[str, Any]:
  246. """Get Docker metrics"""
  247. try:
  248. # Get container count
  249. result = subprocess.run(
  250. ["docker", "ps", "-q"],
  251. capture_output=True,
  252. text=True,
  253. timeout=10
  254. )
  255. if result.returncode == 0:
  256. running_containers = len([line for line in result.stdout.strip().split('\n') if line])
  257. else:
  258. running_containers = None
  259. # Get total containers
  260. result = subprocess.run(
  261. ["docker", "ps", "-aq"],
  262. capture_output=True,
  263. text=True,
  264. timeout=10
  265. )
  266. if result.returncode == 0:
  267. total_containers = len([line for line in result.stdout.strip().split('\n') if line])
  268. else:
  269. total_containers = None
  270. # Get image count
  271. result = subprocess.run(
  272. ["docker", "images", "-q"],
  273. capture_output=True,
  274. text=True,
  275. timeout=10
  276. )
  277. if result.returncode == 0:
  278. image_count = len([line for line in result.stdout.strip().split('\n') if line])
  279. else:
  280. image_count = None
  281. return {
  282. 'docker_containers_running': running_containers,
  283. 'docker_containers_total': total_containers,
  284. 'docker_images_count': image_count
  285. }
  286. except Exception as e:
  287. self.logger.warning(f"Failed to get Docker metrics: {e}")
  288. return {
  289. 'docker_containers_running': None,
  290. 'docker_containers_total': None,
  291. 'docker_images_count': None
  292. }
  293. def _check_services(self) -> Dict[str, bool]:
  294. """Check status of critical services"""
  295. services = ['docker', 'traefik', 'sshd']
  296. status = {}
  297. for service in services:
  298. try:
  299. result = subprocess.run(
  300. ['systemctl', 'is-active', service],
  301. capture_output=True,
  302. text=True,
  303. timeout=5
  304. )
  305. status[service] = result.stdout.strip() == 'active'
  306. except Exception:
  307. status[service] = False
  308. return status
  309. def _create_signature(self, payload: Dict[str, Any]) -> str:
  310. """Create HMAC signature for payload"""
  311. hmac_secret = self.config.get('hmac_secret')
  312. if not hmac_secret:
  313. raise ValueError("HMAC secret not configured")
  314. message = json.dumps(payload, sort_keys=True).encode()
  315. signature = hmac.new(
  316. hmac_secret.encode(),
  317. message,
  318. hashlib.sha256
  319. ).hexdigest()
  320. return signature
  321. async def send_heartbeat(self) -> bool:
  322. """Send heartbeat with metrics to API"""
  323. try:
  324. metrics = self.collect_system_metrics()
  325. signature = self._create_signature(metrics)
  326. headers = {
  327. 'Content-Type': 'application/json',
  328. 'X-Device-Signature': signature,
  329. 'User-Agent': f'WaouwAgent/2.0.0 ({os.uname().sysname})'
  330. }
  331. url = f"{self.config['api_url']}/devices/heartbeat"
  332. async with self.session.post(
  333. url,
  334. json=metrics,
  335. headers=headers,
  336. timeout=aiohttp.ClientTimeout(total=self.config['timeout'])
  337. ) as response:
  338. if response.status == 200:
  339. result = await response.json()
  340. self.logger.debug(f"Heartbeat sent successfully: {response.status}")
  341. # Handle any commands from server
  342. commands = result.get('commands', [])
  343. if commands:
  344. await self._handle_commands(commands)
  345. return True
  346. else:
  347. error_text = await response.text()
  348. self.logger.warning(
  349. f"Heartbeat failed: HTTP {response.status} - {error_text}"
  350. )
  351. return False
  352. except asyncio.TimeoutError:
  353. self.logger.warning("Heartbeat timeout")
  354. return False
  355. except Exception as e:
  356. self.logger.error(f"Heartbeat error: {e}")
  357. return False
  358. async def _handle_commands(self, commands: List[Dict[str, Any]]):
  359. """Handle commands received from server"""
  360. for command in commands:
  361. try:
  362. cmd_type = command.get('type')
  363. cmd_data = command.get('data', {})
  364. self.logger.info(f"Executing command: {cmd_type}")
  365. if cmd_type == 'ping':
  366. self.logger.info("Ping command received")
  367. elif cmd_type == 'restart_service':
  368. service = cmd_data.get('service')
  369. if service in ['docker', 'traefik']:
  370. await self._restart_service(service)
  371. elif cmd_type == 'update_config':
  372. await self._update_config(cmd_data)
  373. else:
  374. self.logger.warning(f"Unknown command type: {cmd_type}")
  375. except Exception as e:
  376. self.logger.error(f"Command execution failed: {e}")
  377. async def _restart_service(self, service_name: str):
  378. """Restart a system service"""
  379. try:
  380. process = await asyncio.create_subprocess_exec(
  381. 'sudo', 'systemctl', 'restart', service_name,
  382. stdout=asyncio.subprocess.PIPE,
  383. stderr=asyncio.subprocess.PIPE
  384. )
  385. stdout, stderr = await process.communicate()
  386. if process.returncode == 0:
  387. self.logger.info(f"Service {service_name} restarted successfully")
  388. else:
  389. self.logger.error(
  390. f"Failed to restart {service_name}: {stderr.decode()}"
  391. )
  392. except Exception as e:
  393. self.logger.error(f"Error restarting service {service_name}: {e}")
  394. async def _update_config(self, new_config: Dict[str, Any]):
  395. """Update agent configuration"""
  396. try:
  397. # Only allow safe configuration updates
  398. allowed_keys = ['heartbeat_interval', 'log_level']
  399. for key, value in new_config.items():
  400. if key in allowed_keys:
  401. self.config[key] = value
  402. self.logger.info(f"Updated config: {key} = {value}")
  403. # Apply log level change immediately
  404. if 'log_level' in new_config:
  405. self.logger.setLevel(getattr(logging, new_config['log_level']))
  406. except Exception as e:
  407. self.logger.error(f"Failed to update config: {e}")
  408. async def run(self):
  409. """Main agent loop"""
  410. self.logger.info(f"Starting WaouW Agent v2.0.0 (Device ID: {self.device_id})")
  411. self.running = True
  412. # Create HTTP session
  413. connector = aiohttp.TCPConnector(limit=10, limit_per_host=5)
  414. self.session = aiohttp.ClientSession(connector=connector)
  415. retry_count = 0
  416. try:
  417. while self.running:
  418. success = await self.send_heartbeat()
  419. if success:
  420. retry_count = 0
  421. await asyncio.sleep(self.config['heartbeat_interval'])
  422. else:
  423. retry_count += 1
  424. if retry_count <= self.config['max_retries']:
  425. delay = self.config['retry_delay'] * retry_count
  426. self.logger.info(f"Retrying in {delay} seconds (attempt {retry_count})")
  427. await asyncio.sleep(delay)
  428. else:
  429. self.logger.warning("Max retries exceeded, continuing with normal interval")
  430. retry_count = 0
  431. await asyncio.sleep(self.config['heartbeat_interval'])
  432. except KeyboardInterrupt:
  433. self.logger.info("Received keyboard interrupt")
  434. finally:
  435. if self.session:
  436. await self.session.close()
  437. self.logger.info("WaouW Agent stopped")
  438. def main():
  439. """Main entry point"""
  440. import argparse
  441. parser = argparse.ArgumentParser(description="WaouW Device Agent v2.0")
  442. parser.add_argument(
  443. '--config', '-c',
  444. help='Configuration file path',
  445. default=DEFAULT_CONFIG['config_file']
  446. )
  447. parser.add_argument(
  448. '--daemon', '-d',
  449. action='store_true',
  450. help='Run as daemon'
  451. )
  452. parser.add_argument(
  453. '--test',
  454. action='store_true',
  455. help='Test mode - send one heartbeat and exit'
  456. )
  457. args = parser.parse_args()
  458. # Create agent
  459. agent = WaouwAgent(args.config)
  460. if args.test:
  461. # Test mode
  462. async def test_heartbeat():
  463. connector = aiohttp.TCPConnector()
  464. agent.session = aiohttp.ClientSession(connector=connector)
  465. try:
  466. success = await agent.send_heartbeat()
  467. print(f"Heartbeat test: {'SUCCESS' if success else 'FAILED'}")
  468. return 0 if success else 1
  469. finally:
  470. await agent.session.close()
  471. exit_code = asyncio.run(test_heartbeat())
  472. sys.exit(exit_code)
  473. # Normal mode
  474. try:
  475. asyncio.run(agent.run())
  476. except KeyboardInterrupt:
  477. pass
  478. except Exception as e:
  479. print(f"Fatal error: {e}")
  480. sys.exit(1)
  481. if __name__ == "__main__":
  482. main()