|
6 | 6 | import os |
7 | 7 | import secrets |
8 | 8 | import signal |
| 9 | +import socket |
9 | 10 | import subprocess |
10 | 11 | import sys |
11 | 12 | import uuid |
@@ -40,6 +41,35 @@ def is_process_running(pid): |
40 | 41 | except Exception: |
41 | 42 | return False |
42 | 43 |
|
| 44 | +def is_port_listening(host, port) -> bool: |
| 45 | + """ |
| 46 | + Check if the specified (host, port) is being listened on. |
| 47 | +
|
| 48 | + Args: |
| 49 | + host: The host to check |
| 50 | + port: The port to check |
| 51 | +
|
| 52 | + Returns: |
| 53 | + True if the (host, port) is being listened on |
| 54 | + """ |
| 55 | + sock = None |
| 56 | + try: |
| 57 | + # Try to connect to the port |
| 58 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 59 | + sock.settimeout(1) |
| 60 | + connected_host = "127.0.0.1" if host == "0.0.0.0" else host |
| 61 | + result = sock.connect_ex((connected_host, port)) |
| 62 | + # result == 0 means connection successful, which means port is in use |
| 63 | + # result != 0 means connection failed, which means port is not in use |
| 64 | + # result == 61 means ECONNREFUSED |
| 65 | + return result == 0 |
| 66 | + except Exception as e: |
| 67 | + logger.error(f"Error checking host {host} and port {port}: {e}") |
| 68 | + return False |
| 69 | + finally: |
| 70 | + if sock: |
| 71 | + sock.close() |
| 72 | + |
43 | 73 |
|
44 | 74 | def read_pid_file(): |
45 | 75 | """read the pid file and return the process id, if the file does not exist or the process is not running, return None""" |
@@ -285,6 +315,15 @@ def router_status(): |
285 | 315 | # check process status |
286 | 316 | pid = read_pid_file() |
287 | 317 | if pid: |
| 318 | + if not is_port_listening(host, port): |
| 319 | + console.print( |
| 320 | + f"[bold yellow]Notice:[/] [bold cyan]{host}:{port}[/] is not yet accepting connections. The service may still be starting up. Please wait a few seconds and try again." |
| 321 | + ) |
| 322 | + console.print( |
| 323 | + f"[yellow]If this message persists after waiting, please check the log for more details.[/] (Log file: {LOG_DIR / 'router_access.log'})" |
| 324 | + ) |
| 325 | + return |
| 326 | + |
288 | 327 | console.print(f"[bold green]MCPRouter is running[/] at http://{host}:{port} (PID: {pid})") |
289 | 328 | share_config = ConfigManager().read_share_config() |
290 | 329 | if share_config.get("pid"): |
|
0 commit comments