diff --git a/docs/compute/runner.md b/docs/compute/runner.md index fca6e65..22de5b0 100644 --- a/docs/compute/runner.md +++ b/docs/compute/runner.md @@ -253,6 +253,17 @@ startup script, and the runner starts within a minute of the rental. `authorized (`VAST_TCP_PORT_22`), which is what the job page shows; Vast's own SSH proxy (`sshN.vast.ai`) works too. Krater refuses to start boxes while the Vast account has any SSH keys, since Vast may install them in every instance. +A host can map the direct port and still refuse every connection to it. On production (2026-11-22), Vast machine +153597 mapped 22/tcp to port 20056, sshd listened on 22 in the container, and Vast said the box was running. The +port refused connections from everywhere, but the proxy reached the same sshd. So the worker tests a running box's +direct port with one TCP connection (`krater.compute.ssh_reach`), only while the box's runner reports from the +current container and Krater's own network is up. A refusal moves the box to the proxy address, and the job page, +`krater ssh` and `krater show` give that address; the box's events say so once (`ssh_proxy`). A timeout decides +nothing. (A host that drops connections, not refuses them, keeps its direct address.) While the port can't be tested (a paused box, a quiet runner), a box moved to the proxy stays there. The +worker tests a working port once per process and a refused one again after 30 minutes, at most 5 new tests a pass. +It never connects to an address that isn't public. The test runs from the worker, so a member whose own network +blocks Vast's direct ports still gets the direct address. + What a member can read inside their box: the container's environment (`/proc/1/environ`) has `KRATER_JOB_TOKEN` (this instance's runner token: it can only report for this box), Vast's `CONTAINER_API_KEY` (it can stop or destroy this one instance; Krater treats that like any unexpected stop) and a `JUPYTER_TOKEN` Vast generates. Boxes are diff --git a/krater/compute/scheduler.py b/krater/compute/scheduler.py index b9f2dc2..32faad6 100644 --- a/krater/compute/scheduler.py +++ b/krater/compute/scheduler.py @@ -41,7 +41,7 @@ from sqlalchemy.orm import Session from krater import net_errors, providers -from krater.compute import launch, market, offers, runner_api, search_quota, spend +from krater.compute import launch, market, offers, runner_api, search_quota, spend, ssh_reach from krater.compute.search_pacing import SearchPacer from krater.config import Settings from krater.models import ( @@ -313,8 +313,12 @@ def __init__( pacer: SearchPacer | None = None, registry: Registry | None = None, network: network_watch.NetworkCheck | None = None, + ssh_check: ssh_reach.SshCheck | None = None, ) -> None: self.session = session + # Asked whether a box's direct SSH port takes connections (`_record_ssh`). Without one (tests, one-off + # passes), the direct port is trusted, as Vast lists it. + self.ssh_check = ssh_check # Asked before acting on a silent runner (`_hold_for_network`). Without one (tests, one-off passes), the # network counts as up. self.network = network @@ -1366,12 +1370,67 @@ def _start_self_stopped(self, row: ComputeInstance) -> None: # -- Boxes ----------------------------------------------------------------------------------------- def _record_ssh(self, row: ComputeInstance, seen: Instance) -> None: - """Where the member's SSH client should connect: the direct port when Vast mapped one, else Vast's proxy.""" + """Where the member's SSH client should connect: the direct port when Vast mapped one and it takes + connections, else Vast's proxy (`krater.compute.ssh_reach`). While the direct port can't be tested, an + address already moved to the proxy stays there.""" + direct = None mapped = (seen.ports or {}).get("22/tcp") or [] if seen.public_ipaddr and mapped and isinstance(mapped[0], dict) and mapped[0].get("HostPort"): - row.ssh_host, row.ssh_port = seen.public_ipaddr, int(mapped[0]["HostPort"]) - elif seen.ssh_host and seen.ssh_port: - row.ssh_host, row.ssh_port = seen.ssh_host, seen.ssh_port + try: + direct = (seen.public_ipaddr, int(mapped[0]["HostPort"])) + except (TypeError, ValueError): + direct = None + proxy = (seen.ssh_host, seen.ssh_port) if seen.ssh_host and seen.ssh_port else None + if direct is None: + if proxy is not None: + row.ssh_host, row.ssh_port = proxy + return + if proxy is None: + row.ssh_host, row.ssh_port = direct + return + works = self._direct_ssh_works(row, seen, direct) + if works is None: + # Untested now: stay on the proxy only if Krater moved it there for a refused direct port. + works = (row.ssh_host, row.ssh_port) == direct or not self._told_ssh_proxy(row) + if works: + row.ssh_host, row.ssh_port = direct + return + if not self._told_ssh_proxy(row): + _event( + self.session, + row.job, + "ssh_proxy", + f"The machine's direct SSH port ({direct[0]}:{direct[1]}) refuses connections, so SSH goes " + f"through {self.provider.title}'s proxy ({proxy[0]}:{proxy[1]}).", + now=self.now, + instance=row, + ) + row.ssh_host, row.ssh_port = proxy + + def _direct_ssh_works(self, row: ComputeInstance, seen: Instance, direct: tuple[str, int]) -> bool | None: + """Whether `direct` takes connections, or `None` when it can't be told now. Only a running box's port is + tested, and only while its runner reports from the current container: sshd starts before the runner, so a + refusal then is the host's doing. Not while Krater's own network is down, or the box is ending.""" + if self.ssh_check is None or row.job.kind is not ComputeJobKind.BOX: + return None + if row.state is not ComputeInstanceState.RUNNING or seen.phase is not Phase.RUNNING or seen.stopping: + return None + if row.destroy_requested_at is not None or row.stop_requested_at is not None: + return None + if row.runner_starts < row.runner_starts_needed or not self._beat_is_fresh(row): + return None + if self.network is not None: + if self._network_problem is False: + self._network_problem = self.network.problem(self.session, now=self.now) + if self._network_problem: + return None + return self.ssh_check.direct_works(row.provider_instance_id or row.label, *direct, now=self.now) + + def _told_ssh_proxy(self, row: ComputeInstance) -> bool: + stmt = sa.select(ComputeEvent.id).where( + ComputeEvent.job_id == row.job_id, ComputeEvent.instance_id == row.id, ComputeEvent.kind == "ssh_proxy" + ) + return self.session.scalar(stmt.limit(1)) is not None def _check_idle(self, row: ComputeInstance, job: ComputeJob, policy: ComputePolicy) -> None: """A box is idle while its runner reports low GPU (and CPU) use and no open session. Idle for the box idle @@ -2152,6 +2211,7 @@ def run_pass( pacer: SearchPacer | None = None, registry: Registry | None = None, network: network_watch.NetworkCheck | None = None, + ssh_check: ssh_reach.SshCheck | None = None, ) -> PassResult: return Scheduler( session, @@ -2163,4 +2223,5 @@ def run_pass( pacer=pacer, registry=registry, network=network, + ssh_check=ssh_check, ).run() diff --git a/krater/compute/ssh_reach.py b/krater/compute/ssh_reach.py new file mode 100644 index 0000000..12c4008 --- /dev/null +++ b/krater/compute/ssh_reach.py @@ -0,0 +1,99 @@ +"""Whether a box's direct SSH port takes connections, so Krater gives members an address that works. + +Vast gives a box two ways in: a direct port on the host's public address (`ports["22/tcp"]`), and its own SSH proxy +(`ssh_host`, `ssh_port`). Krater prefers the direct port: it skips a hop. But a host can list a mapped direct port +that refuses every connection. Seen live 2026-11-22: Vast machine 153597 mapped 22/tcp to port 20056, sshd listened +on 22 in the container and Vast said the box was running, yet the port refused connections from everywhere. The +proxy reached the same sshd. Every box rented there gave its member a dead `krater ssh`. + +So the worker opens a TCP connection to a running box's direct port (`krater.compute.scheduler`, `_record_ssh`): + +- **Refused** (the host answered: nothing is forwarded) means it doesn't work, and Krater records the proxy. The + scheduler asks only while the box's runner reports from the current container, and sshd starts before the runner, + so a refusal then is the host's doing, not a container still starting. +- **Accepted** means it works, and the direct address stays. +- **No answer** (a timeout, an unreachable network, any other error) decides nothing, and the address stays as it + is: the fault may be on the worker's side. + +A host-supplied address that isn't a public one, or a port out of range, can't be what a member connects to, so it +counts as not working without a connection: the worker never connects to a private or loopback address for a host. + +Each answer is kept for the worker's process, per instance and address: an accepted one for good, the others for +`RECHECK`, so a box is tested about twice an hour at most, not every pass (each test is a login attempt sshd logs). +A pass tests at most `PROBES_PER_MINUTE` new addresses; the rest wait for the next pass, so hosts that drop packets +can't stretch the scheduler's pass. + +Framework-free. +""" + +from __future__ import annotations + +import ipaddress +import socket +from datetime import datetime, timedelta +from typing import Protocol + +#: A refusal answers at once; a dropped connection waits this long and decides nothing. +CONNECT_TIMEOUT_SECONDS = 2.0 +#: How long a refusal or no answer is kept before the address is tested again. +RECHECK = timedelta(minutes=30) +#: New tests in one minute (one scheduler pass), so a pass waits at most this many timeouts. +PROBES_PER_MINUTE = 5 +#: Answers kept; past this the oldest are dropped (destroyed instances' answers, mostly). +MAX_KNOWN = 1000 + + +def probe_tcp(host: str, port: int) -> bool | None: + """`True` when a TCP connection to `host:port` opens, `False` when it is refused, `None` with no answer.""" + try: + with socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS): + return True + except ConnectionRefusedError: + return False + except Exception: # noqa: BLE001 - a timeout, no route, a bad address: none of them says the port is closed + return None + + +def reachable_address(host: str, port: int) -> bool: + """Whether `host:port` could be a member's way in: a public IP address and a real port.""" + if not 1 <= port <= 65535: + return False + try: + return ipaddress.ip_address(host).is_global + except (TypeError, ValueError): + return False + + +class SshCheck(Protocol): + def direct_works(self, instance_id: str, host: str, port: int, *, now: datetime) -> bool | None: + """Whether the direct SSH address `host:port` of `instance_id` takes connections; `None` when unknown.""" + + +class LiveSshCheck: + """The worker's check. One instance lives for the worker's process and remembers each answer.""" + + def __init__(self, *, probe=probe_tcp) -> None: + self._probe = probe + self._known: dict[tuple[str, str, int], tuple[bool | None, datetime]] = {} + self._minute: datetime | None = None + self._probes_this_minute = 0 + + def direct_works(self, instance_id: str, host: str, port: int, *, now: datetime) -> bool | None: + if not reachable_address(host, port): + return False + key = (instance_id, host, port) + known = self._known.get(key) + if known is not None and (known[0] is True or now - known[1] < RECHECK): + return known[0] + minute = now.replace(second=0, microsecond=0) + if minute != self._minute: + self._minute, self._probes_this_minute = minute, 0 + if self._probes_this_minute >= PROBES_PER_MINUTE: + return known[0] if known is not None else None + self._probes_this_minute += 1 + answer = self._probe(host, port) + if len(self._known) >= MAX_KNOWN: + for old in sorted(self._known, key=lambda k: self._known[k][1])[: MAX_KNOWN // 10]: + del self._known[old] + self._known[key] = (answer, now) + return answer diff --git a/krater/worker/app.py b/krater/worker/app.py index 66964ad..fbddc57 100644 --- a/krater/worker/app.py +++ b/krater/worker/app.py @@ -18,6 +18,7 @@ from krater.compute import reconcile as compute_reconciler from krater.compute import scheduler as compute_scheduler from krater.compute import search_quota as compute_search_quota +from krater.compute import ssh_reach as compute_ssh_reach from krater.compute import storage_cleanup as compute_storage from krater.compute.search_pacing import SearchPacer from krater.config import get_settings @@ -265,6 +266,10 @@ def price_history_record(timestamp: int) -> None: #: for the process: it remembers whether its outbound test has ever passed here. NETWORK_CHECK = network_watch.LiveNetworkCheck(edge_ping_expected=get_settings().edge_ping_expected) +#: Whether each box's direct SSH port takes connections (`krater.compute.ssh_reach`). One for the process: it +#: remembers each answer, so a box is tested once. +SSH_CHECK = compute_ssh_reach.LiveSshCheck() + #: Only one scheduler pass runs at a time, so a slow pass can't overlap the next minute's and rent twice. COMPUTE_SCHEDULER_LOCK = "compute_scheduler" @@ -289,6 +294,7 @@ def compute_schedule(timestamp: int) -> None: weave_client=get_weave_client(), pacer=SEARCH_PACER, network=NETWORK_CHECK, + ssh_check=SSH_CHECK, registry=get_registry(), ) if result.errors: diff --git a/tests/compute/test_ssh_reach.py b/tests/compute/test_ssh_reach.py new file mode 100644 index 0000000..f6d268f --- /dev/null +++ b/tests/compute/test_ssh_reach.py @@ -0,0 +1,271 @@ +"""A box's SSH address: the direct port while it takes connections, Vast's proxy when the host refuses them.""" + +from __future__ import annotations + +import socket +from datetime import timedelta + +from krater.compute import runner_api, scheduler, ssh_reach +from krater.config import get_settings +from tests.compute.conftest import current_weave +from tests.compute.test_boxes import _box, _events +from tests.compute.test_scheduler import NOW, RUNNER_SHA, SETTINGS, _instance, _pass, _submit, _token + +DIRECT = {"22/tcp": [{"HostIp": "0.0.0.0", "HostPort": "41022"}]} + + +class _Check: + """Answers `answer`, and records each address asked about.""" + + def __init__(self, answer: bool | None) -> None: + self.answer = answer + self.asked: list[tuple[str, str, int]] = [] + + def direct_works(self, instance_id, host, port, *, now): + self.asked.append((instance_id, host, port)) + return self.answer + + +def _checked_pass(db_session, client, check, minute: int) -> None: + scheduler.run_pass( + db_session, + client, + SETTINGS, + now=NOW + timedelta(minutes=minute), + runner_sha256=RUNNER_SHA, + weave_client=current_weave[0], + ssh_check=check, + ) + + +def _running(db_session, client, fake, job): + """`job`'s machine running with a direct port, its runner started and reporting (minute 2).""" + _pass(db_session, client) + row = _instance(db_session, job) + fake.set_status(row.provider_instance_id, "running", public_ipaddr="198.51.100.7", ports=DIRECT) + instance = runner_api.authenticate(db_session, _token(fake, row)) + runner_api.start(db_session, instance, now=NOW + timedelta(minutes=1), settings=get_settings()) + _pass(db_session, client, NOW + timedelta(minutes=2)) + return row + + +def _beat(db_session, row, minute: int) -> None: + runner_api.heartbeat(db_session, row, {"gpu_util": 50, "sessions": 1}, now=NOW + timedelta(minutes=minute)) + + +def _proxy(fake, row) -> tuple[str, int]: + seen = fake.instances[row.provider_instance_id] + return seen["ssh_host"], seen["ssh_port"] + + +def test_a_refused_direct_port_falls_back_to_the_proxy_once(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + check = _Check(False) + + for minute in (3, 4): + _beat(db_session, row, minute) + _checked_pass(db_session, client, check, minute) + + assert (row.ssh_host, row.ssh_port) == _proxy(fake, row) + assert check.asked[0][1:] == ("198.51.100.7", 41022) + assert _events(db_session, job).count("ssh_proxy") == 1 + + +def test_a_working_direct_port_is_kept(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + + _beat(db_session, row, 3) + _checked_pass(db_session, client, _Check(True), 3) + + assert (row.ssh_host, row.ssh_port) == ("198.51.100.7", 41022) + assert "ssh_proxy" not in _events(db_session, job) + + +def test_no_answer_decides_nothing(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + + _beat(db_session, row, 3) + _checked_pass(db_session, client, _Check(None), 3) + + assert (row.ssh_host, row.ssh_port) == ("198.51.100.7", 41022) + assert "ssh_proxy" not in _events(db_session, job) + + +def test_after_the_fallback_an_untested_pass_keeps_the_proxy(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + _beat(db_session, row, 3) + _checked_pass(db_session, client, _Check(False), 3) + + # The runner goes quiet: the port can't be tested now, and the dead direct address must not come back. + check = _Check(True) + _checked_pass(db_session, client, check, 12) + + assert check.asked == [] + assert (row.ssh_host, row.ssh_port) == _proxy(fake, row) + + +def test_a_direct_port_that_works_again_is_used_again(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + _beat(db_session, row, 3) + _checked_pass(db_session, client, _Check(False), 3) + + _beat(db_session, row, 4) + _checked_pass(db_session, client, _Check(True), 4) + assert (row.ssh_host, row.ssh_port) == ("198.51.100.7", 41022) + + _beat(db_session, row, 5) + _checked_pass(db_session, client, _Check(False), 5) + assert (row.ssh_host, row.ssh_port) == _proxy(fake, row) + assert _events(db_session, job).count("ssh_proxy") == 1 + + +def test_the_port_isnt_tested_before_the_runner_starts(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + _pass(db_session, client) + row = _instance(db_session, job) + fake.set_status(row.provider_instance_id, "running", public_ipaddr="198.51.100.7", ports=DIRECT) + check = _Check(False) + + _checked_pass(db_session, client, check, 1) + + assert check.asked == [] + assert (row.ssh_host, row.ssh_port) == ("198.51.100.7", 41022) + + +def test_a_batch_jobs_ports_arent_tested(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _submit(db_session, member, project) + row = _running(db_session, client, fake, job) + check = _Check(False) + + _beat(db_session, row, 3) + _checked_pass(db_session, client, check, 3) + + assert check.asked == [] + + +# -- The live check ------------------------------------------------------------------------------------ + + +def _live(answers): + probed: list[tuple[str, int]] = [] + + def probe(host, port): + probed.append((host, port)) + return answers.pop(0) + + return ssh_reach.LiveSshCheck(probe=probe), probed + + +HOST = "38.114.93.198" + + +def test_a_working_port_is_tested_once() -> None: + check, probed = _live([True]) + + assert check.direct_works("1", HOST, 20056, now=NOW) is True + assert check.direct_works("1", HOST, 20056, now=NOW + timedelta(days=1)) is True + assert probed == [(HOST, 20056)] + + +def test_a_refused_port_is_tested_again_after_the_recheck_time() -> None: + check, probed = _live([False, True]) + + assert check.direct_works("1", HOST, 20056, now=NOW) is False + assert check.direct_works("1", HOST, 20056, now=NOW + timedelta(minutes=5)) is False + assert check.direct_works("1", HOST, 20056, now=NOW + ssh_reach.RECHECK) is True + assert len(probed) == 2 + + +def test_a_pass_tests_only_a_few_new_addresses() -> None: + check, probed = _live([False] * 10) + + answers = [check.direct_works(str(i), HOST, 20000 + i, now=NOW) for i in range(ssh_reach.PROBES_PER_MINUTE + 2)] + + assert answers[-2:] == [None, None] + assert len(probed) == ssh_reach.PROBES_PER_MINUTE + assert check.direct_works("99", HOST, 20099, now=NOW + timedelta(minutes=1)) is False + + +def test_a_private_address_or_a_bad_port_is_never_connected_to() -> None: + check, probed = _live([]) + + assert check.direct_works("1", "127.0.0.1", 22, now=NOW) is False + assert check.direct_works("1", "10.0.0.5", 22, now=NOW) is False + assert check.direct_works("1", "169.254.169.254", 80, now=NOW) is False + assert check.direct_works("1", HOST, 70000, now=NOW) is False + assert check.direct_works("1", "not-an-ip", 22, now=NOW) is False + assert probed == [] + + +def test_the_probe_tells_open_from_refused() -> None: + with socket.socket() as server: + server.bind(("127.0.0.1", 0)) + server.listen() + port = server.getsockname()[1] + assert ssh_reach.probe_tcp("127.0.0.1", port) is True + assert ssh_reach.probe_tcp("127.0.0.1", port) is False + assert ssh_reach.probe_tcp("127.0.0.1", 70000) is None + + +def test_a_paused_box_whose_runner_hasnt_started_again_isnt_tested(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + _beat(db_session, row, 3) + row.runner_starts_needed = row.runner_starts + 1 # what a pause sets: the container restarts on resume + check = _Check(False) + + _checked_pass(db_session, client, check, 3) + + assert check.asked == [] + assert (row.ssh_host, row.ssh_port) == ("198.51.100.7", 41022) + + +def test_a_quiet_runner_means_no_test(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + _running(db_session, client, fake, job) + check = _Check(False) + + _checked_pass(db_session, client, check, 3 + 10) + + assert check.asked == [] + + +def test_no_test_while_krater_s_network_is_down(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + _beat(db_session, row, 3) + check = _Check(False) + + class _Down: + def problem(self, session, *, now): + return "the edge is down" + + scheduler.run_pass( + db_session, + client, + SETTINGS, + now=NOW + timedelta(minutes=3), + runner_sha256=RUNNER_SHA, + weave_client=current_weave[0], + ssh_check=check, + network=_Down(), + ) + + assert check.asked == [] + + +def test_a_proxy_that_changes_host_keeps_the_box_off_the_dead_port(db_session, member, project, client, fake) -> None: # noqa: F811 + job = _box(db_session, member, project) + row = _running(db_session, client, fake, job) + _beat(db_session, row, 3) + _checked_pass(db_session, client, _Check(False), 3) + fake.instances[row.provider_instance_id]["ssh_host"] = "ssh7.vast.ai" + + _checked_pass(db_session, client, _Check(True), 12) # quiet runner: untested + + assert row.ssh_host == "ssh7.vast.ai"