diff --git a/llmhost/cli.py b/llmhost/cli.py index e9a6f0c..85f62bf 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -225,15 +225,23 @@ def cmd_opencode_setup(a): def port_free(port): - # Check both: another program may hold only 127.0.0.1:port, and macOS can still let - # 0.0.0.0:port bind while it does. + """True if nothing is listening on the port, so a server could bind it now.""" + # Something accepting connections on localhost means busy (covers 0.0.0.0 and 127.0.0.1). + c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + c.settimeout(0.5) + try: + if c.connect_ex(("127.0.0.1", port)) == 0: + return False + except OSError: + pass + finally: + c.close() + # Then bind the way servers do, with SO_REUSEADDR: connections from a just-stopped server + # linger in TIME_WAIT for up to a minute, and a plain bind fails because of them even though + # the server will start fine. Check both addresses: another program may hold only one. for addr in ("0.0.0.0", "127.0.0.1"): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - if sys.platform.startswith("linux"): - # Servers bind with SO_REUSEADDR, so connections lingering in TIME_WAIT (e.g. from - # a server that just stopped) don't block them; without it the port looks busy. - # On Linux this still fails if anything is listening. (On macOS it would not.) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.bind((addr, port)) except OSError: @@ -424,8 +432,16 @@ def hf_cache_rm_cmd(repos): def cmd_uninstall(a): # Read the catalog now: --purge deletes it along with the rest of llm-host. cached = cached_catalog_models() + cfg = paths.load_config() or {} for name in service.NAMES: service.uninstall(name) + # Stopping returns before the processes have exited (launchd especially). Wait, so a + # reinstall right after this finds the ports free instead of moving to other ones. + if cfg.get("api_port"): + span = 2 if cfg.get("backend") == "mlx" else 1 + ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else []) + with Spinner("Waiting for the services to exit"): + wait_ports_free(ours, timeout=30) for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"): shutil.rmtree(paths.DATA / d, ignore_errors=True) say("Removed services and backend environments.")