diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index b6b2481..cf99ff6 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -32,7 +32,7 @@ def install(hw, log=print): subprocess.run([u, "venv", "--managed-python", "--python", "3.12", str(VENV)], check=True) spec = os.environ.get("LLMHOST_MLX_SPEC", "mlx-lm") log(f"$ uv pip install {spec}") - subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub[cli]"], check=True) + subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub"], check=True) return {} @@ -174,10 +174,39 @@ def make_handler(inner_port, served_name, context, key, stats): return Proxy +def _kill_stale_servers(inner_port): + """Stop mlx_lm.server processes left behind by an earlier crash of this service. + Only processes running from our own venv are touched.""" + out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"], + capture_output=True, text=True).stdout.split() + for pid in out: + cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout + if str(VENV) in cmd and "mlx_lm" in cmd: + print(f"llm-host: stopping leftover mlx_lm.server (pid {pid}) on port {inner_port}", flush=True) + try: + os.kill(int(pid), signal.SIGTERM) + except OSError: + pass + if out: + time.sleep(2) + + def run_server(cfg, entry, choice, args): - """Start mlx_lm.server as a child on api_port+1 and the auth proxy on api_port.""" + """Start the auth proxy on api_port, then mlx_lm.server as a child on api_port+1.""" port = cfg["api_port"] inner = port + 1 + # Claim the public port first: if it's taken, fail before starting (and orphaning) a child. + stats = Stats() + try: + srv = ThreadingHTTPServer(("0.0.0.0", port), + make_handler(inner, entry["name"], choice.get("est_context", entry["context"]), + paths.api_key(), stats)) + except OSError as e: + print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; " + f"pick a free port with: llmhost setup --api-port ", flush=True) + sys.exit(1) + _kill_stale_servers(inner) + exe = str(VENV / "bin/mlx_lm.server") child = subprocess.Popen([exe, *args]) @@ -191,13 +220,13 @@ def run_server(cfg, entry, choice, args): signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) - stats = Stats() - srv = ThreadingHTTPServer(("0.0.0.0", port), - make_handler(inner, entry["name"], choice.get("est_context", entry["context"]), - paths.api_key(), stats)) - threading.Thread(target=srv.serve_forever, daemon=True).start() - print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True) - rc = child.wait() - print(f"llm-host: mlx_lm.server exited with {rc}", flush=True) + try: + threading.Thread(target=srv.serve_forever, daemon=True).start() + print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True) + rc = child.wait() + print(f"llm-host: mlx_lm.server exited with {rc}", flush=True) + finally: + if child.poll() is None: + child.terminate() time.sleep(1) os._exit(rc or 1) diff --git a/llmhost/cli.py b/llmhost/cli.py index 829cfc1..6791229 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -97,14 +97,24 @@ def cmd_setup(a): if input("Continue with setup? [Y/n] ").strip().lower() not in ("", "y", "yes"): raise SystemExit("aborted") + # Our own services would hold the ports on a re-run; stop them so anything still + # listening belongs to another program. (--no-start leaves a running setup alone.) + if not a.no_start: + for name in service.NAMES: + service.stop(name) + # MLX needs two ports: the proxy, and mlx_lm.server on the next one. + api_span = 2 if p["backend"] == "mlx" else 1 + api_port = choose_port("API", a.api_port, old.get("api_port", 8000), api_span, a.no_start, avoid=set()) + web_port = choose_port("dashboard", a.web_port, old.get("web_port", 8080), 1, a.no_start, + avoid=set(range(api_port, api_port + api_span))) + say(f"\n== Installing {p['backend']} (this can take several minutes) ==") backend_info = {} if a.skip_backend else backend_module(p["backend"]).install(info, say) cfg = { "version": 1, "kind": info["kind"], "backend": p["backend"], "hardware_name": hardware_name(info), "budget_gib": p["budget_gib"], "tp": p["tp"], - "prefer": prefer, "api_port": a.api_port or old.get("api_port", 8000), - "web_port": a.web_port or old.get("web_port", 8080), + "prefer": prefer, "api_port": api_port, "web_port": web_port, "max_jobs": vllm_backend.max_jobs(info["ram_gib"], info["cpus"]), "models": p["models"], "excluded": p["excluded"], "active": active, p["backend"]: {**old.get(p["backend"], {}), **backend_info}, @@ -131,6 +141,55 @@ Done. Connect opencode: run `llmhost opencode-config` and follow what it prints.""") +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. + for addr in ("0.0.0.0", "127.0.0.1"): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind((addr, port)) + except OSError: + return False + finally: + s.close() + return True + + +def port_owner(port): + """Best-effort name of the program listening on a port.""" + try: + out = subprocess.run(["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN"], + capture_output=True, text=True, timeout=5).stdout.splitlines() + if len(out) > 1: + f = out[1].split() + return f"{f[0]} (pid {f[1]})" + except (OSError, subprocess.TimeoutExpired): + pass + return "another program" + + +def choose_port(label, explicit, current, span, no_start, avoid): + """Use the requested/saved port if it's free; otherwise move to the next free one.""" + def ok(p): + return all(port_free(q) and q not in avoid for q in range(p, p + span)) + if explicit: + if not ok(explicit) and not no_start: + raise SystemExit(f"{label} port {explicit} is in use by {port_owner(explicit)}.") + return explicit + if ok(current): + return current + busy = next(q for q in range(current, current + span) if not port_free(q) or q in avoid) + owner = "llm-host's API" if busy in avoid else port_owner(busy) + if no_start: + say(f"Note: {label} port {busy} is in use by {owner}; it must be free before you start llm-host.") + return current + for p in range(current + span, current + 100): + if ok(p): + say(f"Note: {label} port {busy} is in use by {owner}; using port {p} instead.") + return p + raise SystemExit(f"No free port near {current} for the {label}; pass --{'api' if label == 'API' else 'web'}-port.") + + def default_host(): h = socket.gethostname() return h if "." in h else h + ".local"