Coverage for /Users/les/Projects/crackerjack/crackerjack/core/service_watchdog.py: 0%
251 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""
2Service watchdog with timeout protection and automatic recovery.
4This module provides comprehensive monitoring of crackerjack services
5with automatic restart capabilities and hanging prevention.
6"""
8import asyncio
9import logging
10import signal
11import subprocess
12import time
13from dataclasses import dataclass
14from enum import Enum
16from rich.console import Console
17from rich.table import Table
19from ..services.security_logger import get_security_logger
20from .timeout_manager import TimeoutStrategy, get_timeout_manager
22logger = logging.getLogger("crackerjack.service_watchdog")
25class ServiceState(Enum):
26 """Service states."""
28 STOPPED = "stopped"
29 STARTING = "starting"
30 RUNNING = "running"
31 STOPPING = "stopping"
32 FAILED = "failed"
33 TIMEOUT = "timeout"
36@dataclass
37class ServiceConfig:
38 """Configuration for a monitored service."""
40 name: str
41 command: list[str]
42 health_check_url: str | None = None
43 health_check_timeout: float = 5.0
44 startup_timeout: float = 30.0
45 shutdown_timeout: float = 10.0
46 max_restarts: int = 5
47 restart_delay: float = 5.0
48 restart_backoff_multiplier: float = 2.0
49 max_restart_delay: float = 300.0
52@dataclass
53class ServiceStatus:
54 """Status of a monitored service."""
56 config: ServiceConfig
57 state: ServiceState = ServiceState.STOPPED
58 process: subprocess.Popen | None = None
59 last_start_time: float = 0.0
60 last_health_check: float = 0.0
61 restart_count: int = 0
62 consecutive_failures: int = 0
63 last_error: str = ""
64 health_check_failures: int = 0
66 @property
67 def uptime(self) -> float:
68 """Get service uptime in seconds."""
69 if self.state == ServiceState.RUNNING and self.last_start_time > 0:
70 return time.time() - self.last_start_time
71 return 0.0
73 @property
74 def is_healthy(self) -> bool:
75 """Check if service is healthy."""
76 return (
77 self.state == ServiceState.RUNNING
78 and self.process
79 and self.process.poll() is None
80 and self.health_check_failures < 3
81 )
84class ServiceWatchdog:
85 """Watchdog for monitoring and managing services with timeout protection."""
87 def __init__(self, console: Console | None = None) -> None:
88 self.console = console or Console()
89 self.timeout_manager = get_timeout_manager()
90 self.services: dict[str, ServiceStatus] = {}
91 self.is_running = False
92 self.monitor_task: asyncio.Task | None = None
94 # Default service configurations
95 self.default_configs = {
96 "mcp_server": ServiceConfig(
97 name="MCP Server",
98 command=["python", "-m", "crackerjack", "--start-mcp-server"],
99 startup_timeout=30.0,
100 shutdown_timeout=15.0,
101 ),
102 "websocket_server": ServiceConfig(
103 name="WebSocket Server",
104 command=["python", "-m", "crackerjack", "--start-websocket-server"],
105 health_check_url="http://localhost:8675/",
106 health_check_timeout=3.0,
107 startup_timeout=20.0,
108 shutdown_timeout=10.0,
109 ),
110 }
112 def add_service(self, service_id: str, config: ServiceConfig) -> None:
113 """Add a service to monitor."""
114 self.services[service_id] = ServiceStatus(config=config)
115 logger.info(f"Added service {service_id} to watchdog")
117 def remove_service(self, service_id: str) -> None:
118 """Remove a service from monitoring."""
119 if service_id in self.services:
120 asyncio.create_task(self.stop_service(service_id))
121 del self.services[service_id]
122 logger.info(f"Removed service {service_id} from watchdog")
124 async def start_watchdog(self) -> None:
125 """Start the watchdog monitoring."""
126 if self.is_running:
127 return
129 self.is_running = True
131 # Add default services
132 for service_id, config in self.default_configs.items():
133 self.add_service(service_id, config)
135 # Start monitoring task with timeout protection
136 self.monitor_task = asyncio.create_task(self._monitor_services())
138 # Setup signal handlers for graceful shutdown
139 self._setup_signal_handlers()
141 self.console.print("[green]🐕 Service Watchdog started[/green]")
142 logger.info("Service watchdog started")
144 async def stop_watchdog(self) -> None:
145 """Stop the watchdog and all monitored services."""
146 if not self.is_running:
147 return
149 self.is_running = False
151 # Cancel monitoring task
152 if self.monitor_task and not self.monitor_task.done():
153 self.monitor_task.cancel()
154 try:
155 await self.monitor_task
156 except asyncio.CancelledError:
157 pass
159 # Stop all services
160 stop_tasks = [
161 self.stop_service(service_id) for service_id in self.services.keys()
162 ]
163 if stop_tasks:
164 await asyncio.gather(*stop_tasks, return_exceptions=True)
166 self.console.print("[yellow]🐕 Service Watchdog stopped[/yellow]")
167 logger.info("Service watchdog stopped")
169 async def start_service(self, service_id: str) -> bool:
170 """Start a specific service with timeout protection."""
171 if service_id not in self.services:
172 return False
174 service = self.services[service_id]
176 if service.state in (ServiceState.RUNNING, ServiceState.STARTING):
177 return True
179 try:
180 async with self.timeout_manager.timeout_context(
181 f"start_service_{service_id}",
182 timeout=service.config.startup_timeout,
183 strategy=TimeoutStrategy.FAIL_FAST,
184 ):
185 service.state = ServiceState.STARTING
186 service.last_start_time = time.time()
188 # Start the service process with security logging
189 security_logger = get_security_logger()
190 security_logger.log_subprocess_execution(
191 command=service.config.command,
192 cwd=None,
193 env_vars_count=0,
194 purpose="service_watchdog_start",
195 )
197 service.process = subprocess.Popen(
198 service.config.command,
199 stdout=subprocess.PIPE,
200 stderr=subprocess.PIPE,
201 start_new_session=True,
202 )
204 # Wait for process to stabilize
205 await asyncio.sleep(2)
207 # Check if process is still running
208 if service.process.poll() is not None:
209 service.state = ServiceState.FAILED
210 service.last_error = "Process exited immediately"
211 return False
213 # Perform health check if configured
214 if service.config.health_check_url:
215 health_ok = await self._perform_health_check(service)
216 if not health_ok:
217 await self._terminate_process(service)
218 service.state = ServiceState.FAILED
219 service.last_error = "Health check failed"
220 return False
222 service.state = ServiceState.RUNNING
223 service.consecutive_failures = 0
224 service.health_check_failures = 0
226 self.console.print(f"[green]✅ Started {service.config.name}[/green]")
227 logger.info(f"Started service {service_id}")
228 return True
230 except Exception as e:
231 service.state = ServiceState.FAILED
232 service.last_error = str(e)
233 service.consecutive_failures += 1
235 if service.process:
236 await self._terminate_process(service)
238 self.console.print(
239 f"[red]❌ Failed to start {service.config.name}: {e}[/red]"
240 )
241 logger.error(f"Failed to start service {service_id}: {e}")
242 return False
244 async def stop_service(self, service_id: str) -> bool:
245 """Stop a specific service with timeout protection."""
246 if service_id not in self.services:
247 return False
249 service = self.services[service_id]
251 if service.state == ServiceState.STOPPED:
252 return True
254 try:
255 async with self.timeout_manager.timeout_context(
256 f"stop_service_{service_id}",
257 timeout=service.config.shutdown_timeout,
258 strategy=TimeoutStrategy.FAIL_FAST,
259 ):
260 service.state = ServiceState.STOPPING
262 if service.process:
263 await self._terminate_process(service)
265 service.state = ServiceState.STOPPED
266 service.process = None
268 self.console.print(f"[yellow]⏹️ Stopped {service.config.name}[/yellow]")
269 logger.info(f"Stopped service {service_id}")
270 return True
272 except Exception as e:
273 service.state = ServiceState.FAILED
274 service.last_error = str(e)
276 self.console.print(
277 f"[red]❌ Failed to stop {service.config.name}: {e}[/red]"
278 )
279 logger.error(f"Failed to stop service {service_id}: {e}")
280 return False
282 async def _monitor_services(self) -> None:
283 """Main monitoring loop with timeout protection."""
284 while self.is_running:
285 try:
286 async with self.timeout_manager.timeout_context(
287 "monitor_services",
288 timeout=30.0, # Monitor cycle timeout
289 strategy=TimeoutStrategy.GRACEFUL_DEGRADATION,
290 ):
291 # Check each service
292 for service_id, service in self.services.items():
293 if not self.is_running: # Check if shutdown requested
294 break
296 try:
297 await self._check_service_health(service_id, service)
298 except Exception as e:
299 logger.error(f"Error checking service {service_id}: {e}")
301 # Wait before next check cycle
302 await asyncio.sleep(10) # Check every 10 seconds
304 except Exception as e:
305 logger.error(f"Monitor services error: {e}")
306 await asyncio.sleep(30) # Longer delay on error
308 async def _check_service_health(
309 self, service_id: str, service: ServiceStatus
310 ) -> None:
311 """Check health of a single service."""
312 if service.state == ServiceState.RUNNING:
313 # Check if process is still alive
314 if service.process and service.process.poll() is not None:
315 service.state = ServiceState.FAILED
316 service.last_error = (
317 f"Process died with exit code {service.process.returncode}"
318 )
319 service.consecutive_failures += 1
321 self.console.print(f"[red]💀 {service.config.name} process died[/red]")
322 return
324 async def _perform_health_check(self, service: ServiceStatus) -> bool:
325 """Perform HTTP health check with timeout protection."""
326 if not service.config.health_check_url:
327 return True
329 try:
330 import aiohttp
332 async with self.timeout_manager.timeout_context(
333 "health_check",
334 timeout=service.config.health_check_timeout,
335 strategy=TimeoutStrategy.FAIL_FAST,
336 ):
337 async with aiohttp.ClientSession() as session:
338 async with session.get(service.config.health_check_url) as response:
339 return response.status == 200
341 except Exception:
342 return False
344 async def _terminate_process(self, service: ServiceStatus) -> None:
345 """Terminate service process gracefully with timeout."""
346 if not service.process:
347 return
349 try:
350 # Try graceful termination first
351 service.process.terminate()
353 # Wait for graceful shutdown
354 try:
355 await asyncio.wait_for(
356 self._wait_for_process_exit(service.process), timeout=5.0
357 )
358 except TimeoutError:
359 # Force kill if graceful shutdown fails
360 service.process.kill()
361 await asyncio.wait_for(
362 self._wait_for_process_exit(service.process), timeout=2.0
363 )
365 except Exception as e:
366 logger.warning(f"Error terminating process: {e}")
367 # Last resort: force kill
368 try:
369 service.process.kill()
370 except Exception:
371 pass
373 async def _wait_for_process_exit(self, process: subprocess.Popen) -> None:
374 """Wait for process to exit."""
375 while process.poll() is None:
376 await asyncio.sleep(0.1)
378 def _setup_signal_handlers(self) -> None:
379 """Setup signal handlers for graceful shutdown."""
381 def signal_handler(signum, frame):
382 logger.info(f"Received signal {signum}, stopping watchdog...")
383 asyncio.create_task(self.stop_watchdog())
385 signal.signal(signal.SIGINT, signal_handler)
386 signal.signal(signal.SIGTERM, signal_handler)
388 def get_service_status(self, service_id: str) -> ServiceStatus | None:
389 """Get status of a specific service."""
390 return self.services.get(service_id)
392 def get_all_services_status(self) -> dict[str, ServiceStatus]:
393 """Get status of all services."""
394 return self.services.copy()
396 def print_status_report(self) -> None:
397 """Print formatted status report."""
398 self.console.print("\n[bold blue]🐕 Service Watchdog Status[/bold blue]")
399 self.console.print("=" * 50)
401 if not self.services:
402 self.console.print("[dim]No services configured[/dim]")
403 return
405 table = Table()
406 table.add_column("Service")
407 table.add_column("Status")
408 table.add_column("Uptime")
410 for service_id, service in self.services.items():
411 # Status emoji and color
412 if service.state == ServiceState.RUNNING and service.is_healthy:
413 status = "[green]🟢 Running[/green]"
414 elif service.state == ServiceState.STARTING:
415 status = "[yellow]🟡 Starting[/yellow]"
416 elif service.state == ServiceState.STOPPING:
417 status = "[yellow]🟡 Stopping[/yellow]"
418 elif service.state == ServiceState.FAILED:
419 status = "[red]🔴 Failed[/red]"
420 elif service.state == ServiceState.TIMEOUT:
421 status = "[red]⏰ Timeout[/red]"
422 else:
423 status = "[dim]⚫ Stopped[/dim]"
425 # Format uptime
426 uptime = service.uptime
427 if uptime > 3600:
428 uptime_str = f"{uptime / 3600:.1f}h"
429 elif uptime > 60:
430 uptime_str = f"{uptime / 60:.1f}m"
431 elif uptime > 0:
432 uptime_str = f"{uptime:.0f}s"
433 else:
434 uptime_str = "-"
436 table.add_row(service.config.name, status, uptime_str)
438 self.console.print(table)
441# Global service watchdog instance
442_global_watchdog: ServiceWatchdog | None = None
445def get_service_watchdog(console: Console | None = None) -> ServiceWatchdog:
446 """Get global service watchdog instance."""
447 global _global_watchdog
448 if _global_watchdog is None:
449 _global_watchdog = ServiceWatchdog(console)
450 return _global_watchdog