waouw_agent_complete.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. #!/usr/bin/env python3
  2. """
  3. WaouW Device Agent v2.0 COMPLETE
  4. Raspberry Pi monitoring agent avec surveillance complète de tous les services
  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. import socket
  17. import requests
  18. from datetime import datetime
  19. from pathlib import Path
  20. from typing import Dict, List, Optional, Any
  21. import asyncio
  22. import aiohttp
  23. import psutil
  24. import docker
  25. # Configuration
  26. DEFAULT_CONFIG = {
  27. "api_url": "http://localhost:8000/api/v1",
  28. "heartbeat_interval": 30,
  29. "max_retries": 3,
  30. "retry_delay": 5,
  31. "timeout": 30,
  32. "log_level": "INFO",
  33. "device_id_file": "/etc/waouw/device_id",
  34. "config_file": "/etc/waouw/agent.conf",
  35. "log_file": "/var/log/waouw/agent.log",
  36. "enable_docker_monitoring": True,
  37. "enable_email_monitoring": True,
  38. "enable_security_monitoring": True,
  39. "enable_network_monitoring": True
  40. }
  41. # Services à surveiller
  42. MONITORED_SERVICES = {
  43. # Core services
  44. "traefik": {"type": "proxy", "port": 8080, "health_path": "/ping"},
  45. "postgres": {"type": "database", "port": 5432},
  46. "redis": {"type": "cache", "port": 6379},
  47. "backend": {"type": "api", "port": 8000, "health_path": "/health"},
  48. "frontend": {"type": "web", "port": 80},
  49. # Email services
  50. "postfix": {"type": "email", "port": 587, "service": "postfix"},
  51. "dovecot": {"type": "email", "port": 993, "service": "dovecot"},
  52. "roundcube": {"type": "webmail", "port": 80, "health_path": "/"},
  53. "mailadmin": {"type": "email_admin", "port": 80, "health_path": "/"},
  54. # Cloud services
  55. "nextcloud": {"type": "cloud", "port": 80, "health_path": "/status.php"},
  56. "nextcloud_db": {"type": "database", "port": 3306},
  57. # Security services
  58. "fail2ban": {"type": "security", "service": "fail2ban"},
  59. "openvpn": {"type": "vpn", "port": 1194, "service": "openvpn"},
  60. # Monitoring services
  61. "graylog": {"type": "logging", "port": 9000, "health_path": "/api/system/lbstatus"},
  62. "prometheus": {"type": "metrics", "port": 9090, "health_path": "/-/healthy"},
  63. "grafana": {"type": "dashboard", "port": 3000, "health_path": "/api/health"},
  64. # System services
  65. "webmin": {"type": "system", "port": 10000},
  66. "phpmyadmin": {"type": "database_admin", "port": 80},
  67. }
  68. class WaouwAgentComplete:
  69. """WaouW Device Agent avec surveillance complète"""
  70. def __init__(self, config_path: Optional[str] = None):
  71. """Initialize the agent"""
  72. self.config = self._load_config(config_path)
  73. self.device_id = self._get_device_id()
  74. self.session: Optional[aiohttp.ClientSession] = None
  75. self.running = False
  76. self.logger = self._setup_logging()
  77. # Docker client for container monitoring
  78. try:
  79. self.docker_client = docker.from_env() if self.config.get("enable_docker_monitoring") else None
  80. except Exception as e:
  81. self.logger.warning(f"Docker client not available: {e}")
  82. self.docker_client = None
  83. # Metrics cache
  84. self._last_network_stats = None
  85. self._last_disk_stats = None
  86. self._service_status_cache = {}
  87. # Setup signal handlers
  88. signal.signal(signal.SIGTERM, self._signal_handler)
  89. signal.signal(signal.SIGINT, self._signal_handler)
  90. def _load_config(self, config_path: Optional[str] = None) -> Dict[str, Any]:
  91. """Load configuration from file or environment"""
  92. config = DEFAULT_CONFIG.copy()
  93. # Load from file if exists
  94. if config_path and Path(config_path).exists():
  95. try:
  96. with open(config_path, 'r') as f:
  97. file_config = json.load(f)
  98. config.update(file_config)
  99. except Exception as e:
  100. print(f"Error loading config file: {e}")
  101. # Override with environment variables
  102. for key in config:
  103. env_key = f"WAOUW_{key.upper()}"
  104. if env_key in os.environ:
  105. value = os.environ[env_key]
  106. # Convert to appropriate type
  107. if isinstance(config[key], bool):
  108. config[key] = value.lower() in ('true', '1', 'yes', 'on')
  109. elif isinstance(config[key], int):
  110. config[key] = int(value)
  111. else:
  112. config[key] = value
  113. return config
  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 if it doesn't exist
  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_formatter = logging.Formatter(
  124. '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  125. )
  126. file_handler.setFormatter(file_formatter)
  127. logger.addHandler(file_handler)
  128. # Console handler
  129. console_handler = logging.StreamHandler()
  130. console_formatter = logging.Formatter(
  131. '%(levelname)s - %(message)s'
  132. )
  133. console_handler.setFormatter(console_formatter)
  134. logger.addHandler(console_handler)
  135. return logger
  136. def _get_device_id(self) -> str:
  137. """Get or generate device ID"""
  138. device_id_file = Path(self.config["device_id_file"])
  139. if device_id_file.exists():
  140. try:
  141. return device_id_file.read_text().strip()
  142. except Exception as e:
  143. self.logger.warning(f"Error reading device ID: {e}")
  144. # Generate new device ID
  145. device_id = str(uuid.uuid4())
  146. try:
  147. device_id_file.parent.mkdir(parents=True, exist_ok=True)
  148. device_id_file.write_text(device_id)
  149. device_id_file.chmod(0o600)
  150. except Exception as e:
  151. self.logger.warning(f"Error saving device ID: {e}")
  152. return device_id
  153. def _signal_handler(self, signum, frame):
  154. """Handle shutdown signals"""
  155. self.logger.info(f"Received signal {signum}, shutting down...")
  156. self.running = False
  157. def collect_system_metrics(self) -> Dict[str, Any]:
  158. """Collect comprehensive system metrics"""
  159. metrics = {}
  160. try:
  161. # CPU metrics
  162. cpu_percent = psutil.cpu_percent(interval=1)
  163. cpu_count = psutil.cpu_count()
  164. load_avg = psutil.getloadavg() if hasattr(psutil, 'getloadavg') else [0, 0, 0]
  165. metrics["cpu"] = {
  166. "percent": cpu_percent,
  167. "count": cpu_count,
  168. "load_avg_1m": load_avg[0],
  169. "load_avg_5m": load_avg[1],
  170. "load_avg_15m": load_avg[2]
  171. }
  172. # Memory metrics
  173. memory = psutil.virtual_memory()
  174. swap = psutil.swap_memory()
  175. metrics["memory"] = {
  176. "total": memory.total,
  177. "available": memory.available,
  178. "percent": memory.percent,
  179. "used": memory.used,
  180. "free": memory.free,
  181. "swap_total": swap.total,
  182. "swap_used": swap.used,
  183. "swap_percent": swap.percent
  184. }
  185. # Disk metrics
  186. disk_usage = psutil.disk_usage('/')
  187. disk_io = psutil.disk_io_counters()
  188. metrics["disk"] = {
  189. "total": disk_usage.total,
  190. "used": disk_usage.used,
  191. "free": disk_usage.free,
  192. "percent": (disk_usage.used / disk_usage.total) * 100,
  193. "read_bytes": disk_io.read_bytes if disk_io else 0,
  194. "write_bytes": disk_io.write_bytes if disk_io else 0,
  195. "read_count": disk_io.read_count if disk_io else 0,
  196. "write_count": disk_io.write_count if disk_io else 0
  197. }
  198. # Network metrics
  199. network_io = psutil.net_io_counters()
  200. network_connections = len(psutil.net_connections())
  201. metrics["network"] = {
  202. "bytes_sent": network_io.bytes_sent,
  203. "bytes_recv": network_io.bytes_recv,
  204. "packets_sent": network_io.packets_sent,
  205. "packets_recv": network_io.packets_recv,
  206. "errin": network_io.errin,
  207. "errout": network_io.errout,
  208. "dropin": network_io.dropin,
  209. "dropout": network_io.dropout,
  210. "connections": network_connections
  211. }
  212. # Calculate deltas for rates
  213. if self._last_network_stats:
  214. time_delta = time.time() - self._last_network_stats["timestamp"]
  215. if time_delta > 0:
  216. metrics["network"]["bytes_sent_rate"] = (
  217. network_io.bytes_sent - self._last_network_stats["bytes_sent"]
  218. ) / time_delta
  219. metrics["network"]["bytes_recv_rate"] = (
  220. network_io.bytes_recv - self._last_network_stats["bytes_recv"]
  221. ) / time_delta
  222. self._last_network_stats = {
  223. "timestamp": time.time(),
  224. "bytes_sent": network_io.bytes_sent,
  225. "bytes_recv": network_io.bytes_recv
  226. }
  227. # Temperature (Raspberry Pi specific)
  228. try:
  229. with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f:
  230. temp_celsius = float(f.read().strip()) / 1000.0
  231. metrics["temperature"] = {"celsius": temp_celsius}
  232. except (FileNotFoundError, ValueError):
  233. pass
  234. # Boot time and uptime
  235. boot_time = psutil.boot_time()
  236. metrics["uptime"] = {
  237. "boot_time": boot_time,
  238. "uptime_seconds": time.time() - boot_time
  239. }
  240. except Exception as e:
  241. self.logger.error(f"Error collecting system metrics: {e}")
  242. return metrics
  243. def collect_docker_services(self) -> Dict[str, Any]:
  244. """Collect Docker services status"""
  245. if not self.docker_client:
  246. return {}
  247. services = {}
  248. try:
  249. containers = self.docker_client.containers.list(all=True)
  250. for container in containers:
  251. if container.name.startswith('waouw_'):
  252. service_name = container.name.replace('waouw_', '')
  253. # Get container stats
  254. try:
  255. stats = container.stats(stream=False, decode=True)
  256. # Calculate CPU percentage
  257. cpu_delta = (
  258. stats['cpu_stats']['cpu_usage']['total_usage'] -
  259. stats['precpu_stats']['cpu_usage']['total_usage']
  260. )
  261. system_delta = (
  262. stats['cpu_stats']['system_cpu_usage'] -
  263. stats['precpu_stats']['system_cpu_usage']
  264. )
  265. cpu_percent = 0
  266. if system_delta > 0:
  267. cpu_percent = (cpu_delta / system_delta) * len(stats['cpu_stats']['cpu_usage']['percpu_usage']) * 100
  268. # Calculate memory usage
  269. memory_usage = stats['memory_stats'].get('usage', 0)
  270. memory_limit = stats['memory_stats'].get('limit', 0)
  271. memory_percent = (memory_usage / memory_limit * 100) if memory_limit > 0 else 0
  272. services[service_name] = {
  273. "status": container.status,
  274. "health": getattr(container.attrs.get('State', {}), 'Health', {}).get('Status', 'unknown'),
  275. "created": container.attrs['Created'],
  276. "started_at": container.attrs['State'].get('StartedAt'),
  277. "cpu_percent": round(cpu_percent, 2),
  278. "memory_usage_mb": round(memory_usage / 1024 / 1024, 2),
  279. "memory_percent": round(memory_percent, 2),
  280. "restart_count": container.attrs['RestartCount'],
  281. "image": container.image.tags[0] if container.image.tags else "unknown"
  282. }
  283. except Exception as e:
  284. # Fallback for containers without stats
  285. services[service_name] = {
  286. "status": container.status,
  287. "health": "unknown",
  288. "created": container.attrs['Created'],
  289. "started_at": container.attrs['State'].get('StartedAt'),
  290. "restart_count": container.attrs['RestartCount'],
  291. "image": container.image.tags[0] if container.image.tags else "unknown",
  292. "error": str(e)
  293. }
  294. except Exception as e:
  295. self.logger.error(f"Error collecting Docker services: {e}")
  296. return services
  297. def collect_email_metrics(self) -> Dict[str, Any]:
  298. """Collect email services metrics"""
  299. if not self.config.get("enable_email_monitoring"):
  300. return {}
  301. email_metrics = {}
  302. try:
  303. # Check Postfix status
  304. postfix_status = self._check_systemd_service("postfix")
  305. email_metrics["postfix"] = postfix_status
  306. # Check Dovecot status
  307. dovecot_status = self._check_systemd_service("dovecot")
  308. email_metrics["dovecot"] = dovecot_status
  309. # Check mail queue
  310. try:
  311. result = subprocess.run(
  312. ["mailq"],
  313. capture_output=True,
  314. text=True,
  315. timeout=10
  316. )
  317. queue_size = 0
  318. if result.returncode == 0:
  319. lines = result.stdout.strip().split('\n')
  320. if lines and "Mail queue is empty" not in lines[-1]:
  321. # Parse queue size from output
  322. for line in lines:
  323. if "requests" in line:
  324. queue_size = int(line.split()[0])
  325. break
  326. email_metrics["mail_queue_size"] = queue_size
  327. except Exception as e:
  328. self.logger.warning(f"Error checking mail queue: {e}")
  329. email_metrics["mail_queue_size"] = -1
  330. # Check mail logs for errors
  331. try:
  332. result = subprocess.run(
  333. ["grep", "-c", "error\\|Error\\|ERROR", "/var/log/mail.log"],
  334. capture_output=True,
  335. text=True,
  336. timeout=5
  337. )
  338. error_count = int(result.stdout.strip()) if result.returncode == 0 else 0
  339. email_metrics["mail_errors_today"] = error_count
  340. except Exception:
  341. email_metrics["mail_errors_today"] = -1
  342. except Exception as e:
  343. self.logger.error(f"Error collecting email metrics: {e}")
  344. return email_metrics
  345. def collect_security_metrics(self) -> Dict[str, Any]:
  346. """Collect security metrics"""
  347. if not self.config.get("enable_security_monitoring"):
  348. return {}
  349. security_metrics = {}
  350. try:
  351. # Fail2Ban status
  352. fail2ban_status = self._check_systemd_service("fail2ban")
  353. security_metrics["fail2ban"] = fail2ban_status
  354. # Get banned IPs count
  355. try:
  356. result = subprocess.run(
  357. ["fail2ban-client", "status"],
  358. capture_output=True,
  359. text=True,
  360. timeout=10
  361. )
  362. if result.returncode == 0:
  363. # Parse jails
  364. jails = []
  365. for line in result.stdout.split('\n'):
  366. if "Jail list:" in line:
  367. jails_str = line.split("Jail list:")[1].strip()
  368. jails = [j.strip() for j in jails_str.split(',') if j.strip()]
  369. total_banned = 0
  370. jail_stats = {}
  371. for jail in jails:
  372. try:
  373. jail_result = subprocess.run(
  374. ["fail2ban-client", "status", jail],
  375. capture_output=True,
  376. text=True,
  377. timeout=5
  378. )
  379. if jail_result.returncode == 0:
  380. banned_count = 0
  381. for line in jail_result.stdout.split('\n'):
  382. if "Currently banned:" in line:
  383. banned_count = int(line.split(":")[1].strip())
  384. break
  385. jail_stats[jail] = banned_count
  386. total_banned += banned_count
  387. except Exception:
  388. jail_stats[jail] = -1
  389. security_metrics["banned_ips_total"] = total_banned
  390. security_metrics["jails"] = jail_stats
  391. except Exception as e:
  392. self.logger.warning(f"Error checking Fail2Ban status: {e}")
  393. security_metrics["banned_ips_total"] = -1
  394. # UFW firewall status
  395. try:
  396. result = subprocess.run(
  397. ["ufw", "status"],
  398. capture_output=True,
  399. text=True,
  400. timeout=5
  401. )
  402. if result.returncode == 0:
  403. status = "active" if "Status: active" in result.stdout else "inactive"
  404. security_metrics["firewall_status"] = status
  405. else:
  406. security_metrics["firewall_status"] = "unknown"
  407. except Exception:
  408. security_metrics["firewall_status"] = "unknown"
  409. # OpenVPN status
  410. openvpn_status = self._check_systemd_service("openvpn")
  411. security_metrics["openvpn"] = openvpn_status
  412. # Check for recent auth failures
  413. try:
  414. result = subprocess.run(
  415. ["grep", "-c", "authentication failure", "/var/log/auth.log"],
  416. capture_output=True,
  417. text=True,
  418. timeout=5
  419. )
  420. auth_failures = int(result.stdout.strip()) if result.returncode == 0 else 0
  421. security_metrics["auth_failures_today"] = auth_failures
  422. except Exception:
  423. security_metrics["auth_failures_today"] = -1
  424. except Exception as e:
  425. self.logger.error(f"Error collecting security metrics: {e}")
  426. return security_metrics
  427. def collect_network_status(self) -> Dict[str, Any]:
  428. """Collect network connectivity status"""
  429. if not self.config.get("enable_network_monitoring"):
  430. return {}
  431. network_status = {}
  432. try:
  433. # Check internet connectivity
  434. try:
  435. response = requests.get("https://8.8.8.8", timeout=5)
  436. network_status["internet"] = True
  437. except Exception:
  438. network_status["internet"] = False
  439. # Check DNS resolution
  440. try:
  441. socket.gethostbyname("google.com")
  442. network_status["dns"] = True
  443. except Exception:
  444. network_status["dns"] = False
  445. # Get network interfaces
  446. interfaces = {}
  447. for interface_name, interface_addresses in psutil.net_if_addrs().items():
  448. if interface_name != 'lo': # Skip loopback
  449. for address in interface_addresses:
  450. if address.family == socket.AF_INET:
  451. interfaces[interface_name] = {
  452. "ip": address.address,
  453. "netmask": address.netmask,
  454. "broadcast": address.broadcast
  455. }
  456. break
  457. network_status["interfaces"] = interfaces
  458. # Check if services are accessible locally
  459. service_checks = {}
  460. for service_name, service_config in MONITORED_SERVICES.items():
  461. if "port" in service_config:
  462. try:
  463. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  464. sock.settimeout(2)
  465. result = sock.connect_ex(('localhost', service_config["port"]))
  466. service_checks[service_name] = result == 0
  467. sock.close()
  468. except Exception:
  469. service_checks[service_name] = False
  470. network_status["service_ports"] = service_checks
  471. except Exception as e:
  472. self.logger.error(f"Error collecting network status: {e}")
  473. return network_status
  474. def _check_systemd_service(self, service_name: str) -> Dict[str, Any]:
  475. """Check systemd service status"""
  476. try:
  477. result = subprocess.run(
  478. ["systemctl", "is-active", service_name],
  479. capture_output=True,
  480. text=True,
  481. timeout=5
  482. )
  483. is_active = result.stdout.strip() == "active"
  484. result = subprocess.run(
  485. ["systemctl", "is-enabled", service_name],
  486. capture_output=True,
  487. text=True,
  488. timeout=5
  489. )
  490. is_enabled = result.stdout.strip() == "enabled"
  491. return {
  492. "active": is_active,
  493. "enabled": is_enabled,
  494. "status": "running" if is_active else "stopped"
  495. }
  496. except Exception as e:
  497. return {
  498. "active": False,
  499. "enabled": False,
  500. "status": "unknown",
  501. "error": str(e)
  502. }
  503. def _check_service_health(self, service_name: str, service_config: Dict[str, Any]) -> Dict[str, Any]:
  504. """Check service health via HTTP health check"""
  505. if "health_path" not in service_config:
  506. return {"healthy": None, "reason": "No health check configured"}
  507. try:
  508. port = service_config.get("port", 80)
  509. health_path = service_config["health_path"]
  510. url = f"http://localhost:{port}{health_path}"
  511. response = requests.get(url, timeout=5)
  512. healthy = response.status_code == 200
  513. return {
  514. "healthy": healthy,
  515. "status_code": response.status_code,
  516. "response_time_ms": response.elapsed.total_seconds() * 1000
  517. }
  518. except Exception as e:
  519. return {
  520. "healthy": False,
  521. "error": str(e)
  522. }
  523. def create_heartbeat_payload(self) -> Dict[str, Any]:
  524. """Create comprehensive heartbeat payload"""
  525. timestamp = datetime.utcnow().isoformat()
  526. payload = {
  527. "device_id": self.device_id,
  528. "timestamp": timestamp,
  529. "agent_version": "2.0.0-complete",
  530. "system_metrics": self.collect_system_metrics(),
  531. "docker_services": self.collect_docker_services(),
  532. "email_metrics": self.collect_email_metrics(),
  533. "security_metrics": self.collect_security_metrics(),
  534. "network_status": self.collect_network_status()
  535. }
  536. # Add service health checks
  537. service_health = {}
  538. for service_name, service_config in MONITORED_SERVICES.items():
  539. health = self._check_service_health(service_name, service_config)
  540. service_health[service_name] = health
  541. payload["service_health"] = service_health
  542. return payload
  543. def _sign_payload(self, payload: Dict[str, Any]) -> str:
  544. """Sign payload with HMAC"""
  545. secret = os.getenv("DEVICE_HMAC_SECRET", "default_secret")
  546. message = json.dumps(payload, sort_keys=True).encode()
  547. signature = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
  548. return signature
  549. async def send_heartbeat(self) -> bool:
  550. """Send heartbeat to API"""
  551. try:
  552. payload = self.create_heartbeat_payload()
  553. signature = self._sign_payload(payload)
  554. headers = {
  555. "Content-Type": "application/json",
  556. "X-Signature": signature,
  557. "User-Agent": f"WaouW-Agent/2.0-complete"
  558. }
  559. url = f"{self.config['api_url']}/devices/heartbeat"
  560. async with self.session.post(url, json=payload, headers=headers) as response:
  561. if response.status == 200:
  562. result = await response.json()
  563. self.logger.debug(f"Heartbeat sent successfully: {result}")
  564. # Handle any commands from server
  565. if "commands" in result:
  566. await self._handle_commands(result["commands"])
  567. return True
  568. else:
  569. error_text = await response.text()
  570. self.logger.error(f"Heartbeat failed: {response.status} - {error_text}")
  571. return False
  572. except Exception as e:
  573. self.logger.error(f"Error sending heartbeat: {e}")
  574. return False
  575. async def _handle_commands(self, commands: List[Dict[str, Any]]):
  576. """Handle commands from server"""
  577. for command in commands:
  578. try:
  579. cmd_type = command.get("type")
  580. cmd_params = command.get("params", {})
  581. self.logger.info(f"Executing command: {cmd_type}")
  582. if cmd_type == "restart_service":
  583. service_name = cmd_params.get("service")
  584. if service_name in MONITORED_SERVICES:
  585. await self._restart_service(service_name)
  586. elif cmd_type == "update_config":
  587. new_config = cmd_params.get("config", {})
  588. self.config.update(new_config)
  589. elif cmd_type == "collect_logs":
  590. log_lines = cmd_params.get("lines", 100)
  591. await self._send_logs(log_lines)
  592. else:
  593. self.logger.warning(f"Unknown command type: {cmd_type}")
  594. except Exception as e:
  595. self.logger.error(f"Error executing command {command}: {e}")
  596. async def _restart_service(self, service_name: str):
  597. """Restart a service"""
  598. try:
  599. if self.docker_client:
  600. container_name = f"waouw_{service_name}"
  601. try:
  602. container = self.docker_client.containers.get(container_name)
  603. container.restart()
  604. self.logger.info(f"Restarted Docker container: {container_name}")
  605. return
  606. except docker.errors.NotFound:
  607. pass
  608. # Try systemd service
  609. result = subprocess.run(
  610. ["sudo", "systemctl", "restart", service_name],
  611. capture_output=True,
  612. text=True,
  613. timeout=30
  614. )
  615. if result.returncode == 0:
  616. self.logger.info(f"Restarted systemd service: {service_name}")
  617. else:
  618. self.logger.error(f"Failed to restart service {service_name}: {result.stderr}")
  619. except Exception as e:
  620. self.logger.error(f"Error restarting service {service_name}: {e}")
  621. async def _send_logs(self, lines: int):
  622. """Send recent logs to server"""
  623. try:
  624. # Collect logs from various sources
  625. logs = {}
  626. # System logs
  627. result = subprocess.run(
  628. ["journalctl", "--lines", str(lines), "--output", "json"],
  629. capture_output=True,
  630. text=True,
  631. timeout=10
  632. )
  633. if result.returncode == 0:
  634. logs["system"] = result.stdout
  635. # WaouW logs
  636. log_file = Path(self.config["log_file"])
  637. if log_file.exists():
  638. with open(log_file, 'r') as f:
  639. log_lines = f.readlines()
  640. logs["agent"] = ''.join(log_lines[-lines:])
  641. # Send logs to API
  642. payload = {
  643. "device_id": self.device_id,
  644. "timestamp": datetime.utcnow().isoformat(),
  645. "logs": logs
  646. }
  647. url = f"{self.config['api_url']}/devices/logs"
  648. async with self.session.post(url, json=payload) as response:
  649. if response.status == 200:
  650. self.logger.info("Logs sent successfully")
  651. else:
  652. self.logger.error(f"Failed to send logs: {response.status}")
  653. except Exception as e:
  654. self.logger.error(f"Error sending logs: {e}")
  655. async def run(self):
  656. """Main agent loop"""
  657. self.logger.info("Starting WaouW Agent v2.0 COMPLETE")
  658. self.running = True
  659. # Create HTTP session
  660. connector = aiohttp.TCPConnector(limit=10)
  661. timeout = aiohttp.ClientTimeout(total=self.config["timeout"])
  662. self.session = aiohttp.ClientSession(connector=connector, timeout=timeout)
  663. try:
  664. while self.running:
  665. success = await self.send_heartbeat()
  666. if success:
  667. self.logger.debug("Heartbeat cycle completed successfully")
  668. else:
  669. self.logger.warning("Heartbeat cycle failed")
  670. # Wait for next heartbeat
  671. await asyncio.sleep(self.config["heartbeat_interval"])
  672. except Exception as e:
  673. self.logger.error(f"Agent error: {e}")
  674. finally:
  675. if self.session:
  676. await self.session.close()
  677. self.logger.info("WaouW Agent stopped")
  678. async def main():
  679. """Main entry point"""
  680. import argparse
  681. parser = argparse.ArgumentParser(description="WaouW Device Agent v2.0 COMPLETE")
  682. parser.add_argument("--config", help="Configuration file path")
  683. parser.add_argument("--daemon", action="store_true", help="Run as daemon")
  684. parser.add_argument("--test", action="store_true", help="Test mode - single heartbeat")
  685. args = parser.parse_args()
  686. # Create agent
  687. agent = WaouwAgentComplete(args.config)
  688. if args.test:
  689. # Test mode - single heartbeat
  690. agent.logger.info("Running in test mode")
  691. connector = aiohttp.TCPConnector(limit=10)
  692. timeout = aiohttp.ClientTimeout(total=agent.config["timeout"])
  693. agent.session = aiohttp.ClientSession(connector=connector, timeout=timeout)
  694. try:
  695. payload = agent.create_heartbeat_payload()
  696. print("Test payload created:")
  697. print(json.dumps(payload, indent=2))
  698. success = await agent.send_heartbeat()
  699. print(f"Heartbeat test: {'SUCCESS' if success else 'FAILED'}")
  700. finally:
  701. await agent.session.close()
  702. else:
  703. # Normal operation
  704. if args.daemon:
  705. # TODO: Implement proper daemonization
  706. pass
  707. await agent.run()
  708. if __name__ == "__main__":
  709. try:
  710. asyncio.run(main())
  711. except KeyboardInterrupt:
  712. print("\nShutdown requested by user")
  713. except Exception as e:
  714. print(f"Fatal error: {e}")
  715. sys.exit(1)