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

1""" 

2Service watchdog with timeout protection and automatic recovery. 

3 

4This module provides comprehensive monitoring of crackerjack services 

5with automatic restart capabilities and hanging prevention. 

6""" 

7 

8import asyncio 

9import logging 

10import signal 

11import subprocess 

12import time 

13from dataclasses import dataclass 

14from enum import Enum 

15 

16from rich.console import Console 

17from rich.table import Table 

18 

19from ..services.security_logger import get_security_logger 

20from .timeout_manager import TimeoutStrategy, get_timeout_manager 

21 

22logger = logging.getLogger("crackerjack.service_watchdog") 

23 

24 

25class ServiceState(Enum): 

26 """Service states.""" 

27 

28 STOPPED = "stopped" 

29 STARTING = "starting" 

30 RUNNING = "running" 

31 STOPPING = "stopping" 

32 FAILED = "failed" 

33 TIMEOUT = "timeout" 

34 

35 

36@dataclass 

37class ServiceConfig: 

38 """Configuration for a monitored service.""" 

39 

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 

50 

51 

52@dataclass 

53class ServiceStatus: 

54 """Status of a monitored service.""" 

55 

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 

65 

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 

72 

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 ) 

82 

83 

84class ServiceWatchdog: 

85 """Watchdog for monitoring and managing services with timeout protection.""" 

86 

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 

93 

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 } 

111 

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") 

116 

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") 

123 

124 async def start_watchdog(self) -> None: 

125 """Start the watchdog monitoring.""" 

126 if self.is_running: 

127 return 

128 

129 self.is_running = True 

130 

131 # Add default services 

132 for service_id, config in self.default_configs.items(): 

133 self.add_service(service_id, config) 

134 

135 # Start monitoring task with timeout protection 

136 self.monitor_task = asyncio.create_task(self._monitor_services()) 

137 

138 # Setup signal handlers for graceful shutdown 

139 self._setup_signal_handlers() 

140 

141 self.console.print("[green]🐕 Service Watchdog started[/green]") 

142 logger.info("Service watchdog started") 

143 

144 async def stop_watchdog(self) -> None: 

145 """Stop the watchdog and all monitored services.""" 

146 if not self.is_running: 

147 return 

148 

149 self.is_running = False 

150 

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 

158 

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) 

165 

166 self.console.print("[yellow]🐕 Service Watchdog stopped[/yellow]") 

167 logger.info("Service watchdog stopped") 

168 

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 

173 

174 service = self.services[service_id] 

175 

176 if service.state in (ServiceState.RUNNING, ServiceState.STARTING): 

177 return True 

178 

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() 

187 

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 ) 

196 

197 service.process = subprocess.Popen( 

198 service.config.command, 

199 stdout=subprocess.PIPE, 

200 stderr=subprocess.PIPE, 

201 start_new_session=True, 

202 ) 

203 

204 # Wait for process to stabilize 

205 await asyncio.sleep(2) 

206 

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 

212 

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 

221 

222 service.state = ServiceState.RUNNING 

223 service.consecutive_failures = 0 

224 service.health_check_failures = 0 

225 

226 self.console.print(f"[green]✅ Started {service.config.name}[/green]") 

227 logger.info(f"Started service {service_id}") 

228 return True 

229 

230 except Exception as e: 

231 service.state = ServiceState.FAILED 

232 service.last_error = str(e) 

233 service.consecutive_failures += 1 

234 

235 if service.process: 

236 await self._terminate_process(service) 

237 

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 

243 

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 

248 

249 service = self.services[service_id] 

250 

251 if service.state == ServiceState.STOPPED: 

252 return True 

253 

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 

261 

262 if service.process: 

263 await self._terminate_process(service) 

264 

265 service.state = ServiceState.STOPPED 

266 service.process = None 

267 

268 self.console.print(f"[yellow]⏹️ Stopped {service.config.name}[/yellow]") 

269 logger.info(f"Stopped service {service_id}") 

270 return True 

271 

272 except Exception as e: 

273 service.state = ServiceState.FAILED 

274 service.last_error = str(e) 

275 

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 

281 

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 

295 

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}") 

300 

301 # Wait before next check cycle 

302 await asyncio.sleep(10) # Check every 10 seconds 

303 

304 except Exception as e: 

305 logger.error(f"Monitor services error: {e}") 

306 await asyncio.sleep(30) # Longer delay on error 

307 

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 

320 

321 self.console.print(f"[red]💀 {service.config.name} process died[/red]") 

322 return 

323 

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 

328 

329 try: 

330 import aiohttp 

331 

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 

340 

341 except Exception: 

342 return False 

343 

344 async def _terminate_process(self, service: ServiceStatus) -> None: 

345 """Terminate service process gracefully with timeout.""" 

346 if not service.process: 

347 return 

348 

349 try: 

350 # Try graceful termination first 

351 service.process.terminate() 

352 

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 ) 

364 

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 

372 

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) 

377 

378 def _setup_signal_handlers(self) -> None: 

379 """Setup signal handlers for graceful shutdown.""" 

380 

381 def signal_handler(signum, frame): 

382 logger.info(f"Received signal {signum}, stopping watchdog...") 

383 asyncio.create_task(self.stop_watchdog()) 

384 

385 signal.signal(signal.SIGINT, signal_handler) 

386 signal.signal(signal.SIGTERM, signal_handler) 

387 

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) 

391 

392 def get_all_services_status(self) -> dict[str, ServiceStatus]: 

393 """Get status of all services.""" 

394 return self.services.copy() 

395 

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) 

400 

401 if not self.services: 

402 self.console.print("[dim]No services configured[/dim]") 

403 return 

404 

405 table = Table() 

406 table.add_column("Service") 

407 table.add_column("Status") 

408 table.add_column("Uptime") 

409 

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]" 

424 

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 = "-" 

435 

436 table.add_row(service.config.name, status, uptime_str) 

437 

438 self.console.print(table) 

439 

440 

441# Global service watchdog instance 

442_global_watchdog: ServiceWatchdog | None = None 

443 

444 

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