Coverage for /Users/les/Projects/crackerjack/crackerjack/services/server_manager.py: 0%
140 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
1import os
2import signal
3import sys
4import time
5import typing as t
6from pathlib import Path
8from rich.console import Console
10from .secure_subprocess import execute_secure_subprocess
11from .security_logger import get_security_logger
14def find_mcp_server_processes() -> list[dict[str, t.Any]]:
15 """Find running MCP server processes using secure subprocess execution."""
16 security_logger = get_security_logger()
18 try:
19 # Use secure subprocess execution with validation
20 result = execute_secure_subprocess(
21 command=["ps", "aux"],
22 capture_output=True,
23 text=True,
24 check=True,
25 timeout=10.0, # 10 second timeout for process listing
26 )
28 processes: list[dict[str, t.Any]] = []
29 str(Path.cwd())
31 for line in result.stdout.splitlines():
32 if "crackerjack" in line and "- - start - mcp-server" in line:
33 parts = line.split()
34 if len(parts) >= 11:
35 try:
36 pid = int(parts[1])
37 processes.append(
38 {
39 "pid": pid,
40 "command": " ".join(parts[10:]),
41 "user": parts[0],
42 "cpu": parts[2],
43 "mem": parts[3],
44 },
45 )
46 except (ValueError, IndexError):
47 continue
49 return processes
51 except Exception as e:
52 security_logger.log_subprocess_failure(
53 command=["ps", "aux"],
54 exit_code=-1,
55 error_output=str(e),
56 )
57 return []
60def find_websocket_server_processes() -> list[dict[str, t.Any]]:
61 """Find running WebSocket server processes using secure subprocess execution."""
62 security_logger = get_security_logger()
64 try:
65 # Use secure subprocess execution with validation
66 result = execute_secure_subprocess(
67 command=["ps", "aux"],
68 capture_output=True,
69 text=True,
70 check=True,
71 timeout=10.0, # 10 second timeout for process listing
72 )
74 processes: list[dict[str, t.Any]] = []
76 for line in result.stdout.splitlines():
77 if "crackerjack" in line and "- - start - websocket-server" in line:
78 parts = line.split()
79 if len(parts) >= 11:
80 try:
81 pid = int(parts[1])
82 processes.append(
83 {
84 "pid": pid,
85 "command": " ".join(parts[10:]),
86 "user": parts[0],
87 "cpu": parts[2],
88 "mem": parts[3],
89 },
90 )
91 except (ValueError, IndexError):
92 continue
94 return processes
96 except Exception as e:
97 security_logger.log_subprocess_failure(
98 command=["ps", "aux"],
99 exit_code=-1,
100 error_output=str(e),
101 )
102 return []
105def stop_process(pid: int, force: bool = False) -> bool:
106 try:
107 if force:
108 os.kill(pid, signal.SIGKILL)
109 else:
110 os.kill(pid, signal.SIGTERM)
112 for _ in range(10):
113 try:
114 os.kill(pid, 0)
115 time.sleep(0.5)
116 except OSError:
117 return True
119 if not force:
120 os.kill(pid, signal.SIGKILL)
121 time.sleep(1)
123 return True
125 except (OSError, ProcessLookupError):
126 return True
129def stop_mcp_server(console: Console | None = None) -> bool:
130 if console is None:
131 console = Console()
133 processes = find_mcp_server_processes()
135 if not processes:
136 console.print("[yellow]⚠️ No MCP server processes found[/ yellow]")
137 return True
139 success = True
140 for proc in processes:
141 console.print(f"🛑 Stopping MCP server process {proc['pid']}")
142 if stop_process(proc["pid"]):
143 console.print(f"✅ Stopped process {proc['pid']}")
144 else:
145 console.print(f"❌ Failed to stop process {proc['pid']}")
146 success = False
148 return success
151def stop_websocket_server(console: Console | None = None) -> bool:
152 if console is None:
153 console = Console()
155 processes = find_websocket_server_processes()
157 if not processes:
158 console.print("[yellow]⚠️ No WebSocket server processes found[/ yellow]")
159 return True
161 success = True
162 for proc in processes:
163 console.print(f"🛑 Stopping WebSocket server process {proc['pid']}")
164 if stop_process(proc["pid"]):
165 console.print(f"✅ Stopped process {proc['pid']}")
166 else:
167 console.print(f"❌ Failed to stop process {proc['pid']}")
168 success = False
170 return success
173def stop_all_servers(console: Console | None = None) -> bool:
174 if console is None:
175 console = Console()
177 mcp_success = stop_mcp_server(console)
178 websocket_success = stop_websocket_server(console)
180 return mcp_success and websocket_success
183def restart_mcp_server(
184 websocket_port: int | None = None,
185 console: Console | None = None,
186) -> bool:
187 if console is None:
188 console = Console()
190 console.print("[bold cyan]🔄 Restarting MCP server...[/ bold cyan]")
192 stop_mcp_server(console)
194 console.print("⏳ Waiting for cleanup...")
195 time.sleep(2)
197 console.print("🚀 Starting new MCP server...")
198 try:
199 # Build command with proper argument formatting
200 cmd = [sys.executable, "-m", "crackerjack", "--start-mcp-server"]
201 if websocket_port:
202 cmd.extend(["--websocket-port", str(websocket_port)])
204 # Use secure subprocess execution for server restart
205 import subprocess
207 subprocess.Popen(
208 cmd,
209 stdout=subprocess.DEVNULL,
210 stderr=subprocess.DEVNULL,
211 start_new_session=True,
212 )
214 # Log the secure server start
215 security_logger = get_security_logger()
216 security_logger.log_subprocess_execution(
217 command=cmd,
218 cwd=None,
219 env_vars_count=0,
220 purpose="mcp_server_restart",
221 )
223 console.print("✅ MCP server restart initiated")
224 return True
226 except Exception as e:
227 console.print(f"❌ Failed to restart MCP server: {e}")
228 return False
231def list_server_status(console: Console | None = None) -> None:
232 if console is None:
233 console = Console()
235 console.print("[bold cyan]📊 Crackerjack Server Status[/ bold cyan]")
237 mcp_processes = find_mcp_server_processes()
238 websocket_processes = find_websocket_server_processes()
240 if mcp_processes:
241 console.print("\n[bold green]MCP Servers: [/ bold green]")
242 for proc in mcp_processes:
243 console.print(
244 f" • PID {proc['pid']} - CPU: {proc['cpu']}%-Memory: {proc['mem']}%",
245 )
246 console.print(f" Command: {proc['command']}")
247 else:
248 console.print("\n[yellow]MCP Servers: None running[/ yellow]")
250 if websocket_processes:
251 console.print("\n[bold green]WebSocket Servers: [/ bold green]")
252 for proc in websocket_processes:
253 console.print(
254 f" • PID {proc['pid']} - CPU: {proc['cpu']}%-Memory: {proc['mem']}%",
255 )
256 console.print(f" Command: {proc['command']}")
257 else:
258 console.print("\n[yellow]WebSocket Servers: None running[/ yellow]")
260 if not mcp_processes and not websocket_processes:
261 console.print("\n[dim]No crackerjack servers currently running[/ dim]")