diff --git a/tests/test_image_adopt.py b/tests/test_image_adopt.py new file mode 100644 index 000000000..5d7f6ae23 --- /dev/null +++ b/tests/test_image_adopt.py @@ -0,0 +1,690 @@ +"""``yeto image adopt`` steps 1-4 (own-cluster-fleet-stability 7.2): manifest and digest, +the probe on one node, the fit to every node, the parallel pre-pull with the image root +check. Each failure stops at its step, names the reason and leaves the catalog alone.""" + +from __future__ import annotations + +import dataclasses +import json +import shlex +import subprocess +import urllib.error +import urllib.parse + +import pytest + +from tests.test_cluster_preflight import Behavior, FakeCluster, b300, disk_line +from yeto.launch import image_adopt as ia +from yeto.launch import image_manifest as im +from yeto.launch import site_images as si + +DIGEST = "sha256:" + "d" * 64 +TAGGED = "reg.example/site/miles-new:k99" +PINNED = f"reg.example/site/miles-new@{DIGEST}" +MILES_FACTS = {"uname_m": "x86_64", "python": "3.12.3", "python_path": "/usr/bin/python3", "torch": "2.9.1+cu130", + "cuda": "13.0", "hip": None, "arch_list": ["sm_90", "sm_100", "sm_103", "compute_103"], + "packages": {"torch": "2.9.1+cu130", "megatron-core": "0.15.0", "miles": "0.3.0", "ray": "2.52.0"}, + "lock": {"image": "miles-new", "versions": {"torch": "2.9.1"}}} + + +class _Resp: + def __init__(self, status, headers=None, body=b""): + self.status, self.headers, self._body = status, headers or {}, body + + def read(self): + return self._body + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def registry(manifests: dict[str, int], digest: str = DIGEST): + """A registry that answers a manifest HEAD by tag or digest (anonymous).""" + seen = [] + + def urlopen(req, timeout=None): + seen.append(req.full_url) + reference = req.full_url.rsplit("/manifests/", 1)[1] + code = manifests.get(reference, 404) + if code == 200: + return _Resp(200, {"Docker-Content-Digest": digest}) + raise urllib.error.HTTPError(req.full_url, code, "x", {}, None) + + return urlopen, seen + + +def probe_out(facts=None, **over): + facts = {**MILES_FACTS, **(facts or {}), **over} + return "\n".join(f"{ia.FACT} {k} {json.dumps(v)}" for k, v in facts.items() if v is not None) + "\n" + + +class FakeNodes(FakeCluster): + """The preflight's fake B300 cluster plus the adoption probe.""" + + def __init__(self, nodes, *, probe=None, probe_rc=0, bare=None, busy=None, **per_node): + super().__init__(nodes, **per_node) + self.probe = probe_out() if probe is None else probe + self.bare = bare # the probe's output without cards (None: the same as with them) + self.probe_rc = probe_rc + self.busy = f"{ia.BUSY_MARK} tool cuda\n" if busy is None else busy + + def run(self, node, script, *, timeout=300.0): + if ia.BUSY_MARK in script: + self.scripts.append((node.name, "busy")) + return self.done(0, self.busy) + if script.startswith(("podman pull", "sudo -n podman pull")): + self.scripts.append((node.name, script)) + return self.done(*self.b[node.name].pull) + if ia.FACT in script: + cards = "--gpus" in shlex.split(script) + self.scripts.append((node.name, "probe+cards" if cards else "probe")) + return self.done(self.probe_rc, self.bare if self.bare is not None and not cards else self.probe) + return super().run(node, script, timeout=timeout) + + def kinds(self): + return [(s if s in ("probe", "probe+cards", "busy") else s.split()[0] + " " + s.split()[1] + if s.startswith("docker") else "host" if "@@yeto-section" in s else s.split()[0]) + for _, s in self.scripts] + + +def request(nodes, tmp_path, **kw): + return ia.AdoptRequest(ref=kw.pop("ref", TAGGED), model="moonshotai/Kimi-K3.1-Pro", role=kw.pop("role", "trainer"), + nodes=tuple(nodes), catalog=str(tmp_path / "site-images.yaml"), **kw) + + +def adopter(req, ops, *, manifests=None, smoke=None): + opener, seen = registry(manifests or {"k99": 200, DIGEST: 200}) + a = ia.Adopter(req, ops=ops, smoke=smoke, urlopen=opener, login=None, log=lambda m: None, + clock=lambda: FakeCluster.NOW) + a.seen = seen + return a + + +def passing_smoke(calls=None): + def smoke(adopter, ref, facts, engine): + if calls is not None: + calls.append((ref, engine)) + return ia.StepResult("smoke", True, "one step trained, checkpoint saved and loaded", 1.0, + {"layers": 4}) + return smoke + + +@pytest.fixture(autouse=True) +def _registry_on(monkeypatch): + monkeypatch.delenv(im.CHECK_ENV, raising=False) # tests here pass their own fake registry + + +@pytest.fixture +def catalog_before(tmp_path): + path = tmp_path / "site-images.yaml" + path.write_text("version: 1\nimages: []\n") + return path + + +# -- step 1: manifest ----------------------------------------------------------------- + + +def test_a_tag_is_pinned_to_the_registry_digest(): + opener, seen = registry({"k99": 200}) + assert ia.pin(TAGGED, urlopen=opener) == PINNED + assert seen == ["https://reg.example/v2/site/miles-new/manifests/k99"] + opener, _ = registry({DIGEST: 200}) + assert ia.pin("docker:" + PINNED, urlopen=opener) == PINNED + assert im.pin_digest("reg.example:5000/a/b:v1", urlopen=registry({"v1": 200})[0]) == \ + (im.PRESENT, f"reg.example:5000/a/b@{DIGEST}") + + +def test_a_registry_without_a_digest_header_is_not_pinned(): + def urlopen(req, timeout=None): + return _Resp(200, {}) + assert im.pin_digest(TAGGED, urlopen=urlopen)[0] == im.UNKNOWN + + +def test_without_the_registry_check_only_a_digest_is_taken(monkeypatch): + monkeypatch.setenv(im.CHECK_ENV, "off") + assert ia.pin(PINNED) == PINNED + with pytest.raises(ia.AdoptError, match="a tag cannot be pinned"): + ia.pin(TAGGED) + + +def test_a_missing_manifest_stops_before_any_node(tmp_path, catalog_before): + nodes = [b300(i) for i in range(2)] + ops = FakeNodes(nodes) + a = adopter(request(nodes, tmp_path), ops, manifests={"k99": 404}, smoke=passing_smoke()) + with pytest.raises(ia.AdoptError) as error: + a.run() + assert error.value.step == "manifest" + assert "the registry has no manifest for reg.example/site/miles-new:k99" in str(error.value) + assert ops.scripts == [] # no node was asked anything + assert catalog_before.read_text() == "version: 1\nimages: []\n" + assert [(s.name, s.ok) for s in a.report.steps] == [("manifest", False)] + + +def test_a_denied_manifest_names_the_registry_login(tmp_path): + with pytest.raises(ia.AdoptError, match="give the registry login"): + ia.pin(TAGGED, urlopen=registry({"k99": 403})[0]) + + +# -- step 2: probe -------------------------------------------------------------------- + + +def test_the_probe_runs_the_image_without_cards_and_reads_its_facts(): + node = b300(0) + argv = shlex.split(ia.probe_script(PINNED, node)) + assert argv[:6] == ["docker", "run", "--rm", "--network", "host", "--entrypoint"] and PINNED in argv + assert "torch._C._cuda_getArchFlags()" in argv[-1] # the build flags: no card needed + with_cards = shlex.split(ia.probe_script(PINNED, node, cards=True)) + assert list(node.docker_args) == with_cards[5:5 + len(node.docker_args)] # the fallback: the node's flags + from yeto.launch.node_inventory import NodeProfile + + podman = NodeProfile.from_node(b300(0, docker_args=()), container="podman") + argv = shlex.split(ia.probe_script(PINNED, podman, cards=True)) + assert argv[:3] == ["podman", "run", "--rm"] and ["--device", "nvidia.com/gpu=all"] == argv[5:7] + with pytest.raises(ia.AdoptError, match="node b300-0 runs no container engine"): + ia.probe_script(PINNED, b300(0, runtime="rootfs")) + facts = ia.parse_probe(probe_out() + "noise line\nYETO_IMAGE_FACT bad {not json\n") + assert (facts.cpu_arch, facts.python, facts.cuda, facts.arch_list) == ( + "x86_64", "3.12.3", "13.0", ("sm_90", "sm_100", "sm_103", "compute_103")) + assert facts.arch_source is None and ia.parse_probe(probe_out(arch_source="build_flags")).arch_source == \ + "build_flags" + assert facts.versions() == {"python": "3.12.3", "python_path": "/usr/bin/python3", "torch": "2.9.1+cu130", + "cuda": "13.0", "megatron-core": "0.15.0", "miles": "0.3.0", "ray": "2.52.0", + "image_lock": "miles-new"} + + +def test_the_probe_body_runs_under_bash_without_torch(tmp_path): + """The script inside the container: uname, no lock, a Python without torch.""" + argv = shlex.split(ia.probe_script(PINNED, b300(0))) + inner = argv[argv.index("-c") + 1] + done = subprocess.run(["bash", "-c", inner], capture_output=True, text=True, timeout=60) + facts = ia.parse_probe(done.stdout) + assert done.returncode == 0, done.stderr + assert facts.python and facts.cpu_arch in ("x86_64", "aarch64", "arm64") + + +def test_a_failed_probe_names_the_node_and_docker_line(tmp_path, catalog_before): + nodes = [b300(0)] + ops = FakeNodes(nodes, probe="docker: Error response from daemon: manifest unknown: manifest unknown\n", + probe_rc=125) + with pytest.raises(ia.AdoptError, match=r"step probe failed: node b300-0: docker run of .* failed \(rc 125\): " + r"docker: Error response from daemon: manifest unknown"): + adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +# -- step 3: fit ---------------------------------------------------------------------- + + +def test_an_image_built_above_the_nodes_card_stops_at_fit(tmp_path, catalog_before): + a100 = [b300(i, card="A100-80GB", hbm_gib=80.0) for i in range(2)] + ops = FakeNodes(a100, probe=probe_out(arch_list=["sm_90", "sm_100"])) + a = adopter(request(a100, tmp_path), ops, smoke=passing_smoke()) + with pytest.raises(ia.AdoptError) as error: + a.run() + assert error.value.step == "fit" + assert "the image is built for sm_90/sm_100; node b300-0 has A100-80GB (sm80) (CUDA binary compatibility: " \ + "a cubin sm_XY runs on compute capability X.Z with Z >= Y" in error.value.reason + assert "node b300-1 has A100-80GB (sm80)" in error.value.reason + assert ops.kinds() == ["date", "host", "busy", "probe"] # the probe node's checks, nothing pulled + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +@pytest.mark.parametrize("archs, card, ok, note", [ + (["sm_90", "compute_90"], "B300", True, ia.PTX_RULE_NOTE), # PTX of sm90 compiles on sm103 + (["sm_100"], "B300", True, ia.MINOR_RULE_NOTE), # a 10.0 cubin runs on 10.3 + (["sm_80"], "A10G", True, ia.MINOR_RULE_NOTE), # an 8.0 cubin runs on 8.6 + (["sm_86"], "A100", False, None), # not on a lower minor + (["sm_100a"], "B300", False, None), # an arch-specific cubin: only 10.0 + (["sm_90a"], "H100", True, None), + (["sm_120"], "B300", False, None), # another major + (["sm_90", "compute_90a"], "B300", False, None), # arch-specific PTX: no forward JIT + (["compute_103a"], "B300", True, ia.PTX_RULE_NOTE), + (["sm_90", "compute_120"], "B300", False, None), # PTX of a newer card: no backward JIT + (["sm_100f"], "B300", True, ia.MINOR_RULE_NOTE), # a family cubin of 10.x + (["sm_90", "compute_100f"], "B300", True, ia.PTX_RULE_NOTE), # family PTX within 10.x + (["sm_90", "compute_100f"], "RTX-PRO-6000", False, None), # not across majors (sm120) + (["sm_90", "compute_103f"], "B200", False, None), # not to a lower minor + (["sm_80", "sm_90"], "H100", True, None), + (["sm_90", "sm_100", "sm_103"], "B300", True, None), + (["gfx942"], "MI355X", False, None), + (["gfx942", "gfx950"], "MI355X", True, None), + (["gfx950:sramecc+:xnack-"], "MI355X", True, None), # a target's feature suffix + ([], "B300", False, None), # no cards seen in the probe +]) +def test_card_arch_rules(archs, card, ok, note): + facts = ia.parse_probe(probe_out(arch_list=archs)) + family = "rocm" if card.startswith("MI") else "cuda" + node = b300(0, card=card, device_family=family) + problem, how = ia.card_arch_fit(facts, node) + assert (problem is None) is ok, problem + assert (note in how) if note else how is None + assert (ia.card_arch_problem(facts, node) is None) is ok + + +@pytest.mark.parametrize("archs", [["sm_100"], ["sm_90", "compute_90"], ["compute_103"]]) +def test_strict_arch_wants_the_exact_cubin(archs): + facts = ia.parse_probe(probe_out(arch_list=archs)) + problem, _ = ia.card_arch_fit(facts, b300(0), strict=True) + assert problem.startswith("--strict-arch: the image is built for") and "no cubin of exactly sm103" in problem + assert ia.card_arch_fit(ia.parse_probe(probe_out(arch_list=["sm_103a"])), b300(0), strict=True) == (None, None) + + +def test_the_node_profile_card_arch_wins_over_the_card(): + from yeto.launch.node_inventory import NodeProfile + + node = NodeProfile.from_node(b300(0), card_arch="sm100") + facts = ia.parse_probe(probe_out(arch_list=["sm_100"])) + assert ia.card_arch_fit(facts, node) == (None, None) and ia.node_card_arch(node) == "sm100" + + +def test_a_minor_rule_pass_is_noted_in_the_fit_and_the_evidence(tmp_path): + nodes = [b300(i) for i in range(2)] + ops = FakeNodes(nodes, probe=probe_out(arch_list=["sm_90", "sm_100"])) + report = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + fit = next(s for s in report.steps if s.name == "fit") + assert ia.MINOR_RULE_NOTE in fit.detail and len(fit.data["notes"]) == 2 + (rec,) = si.load(tmp_path / "site-images.yaml") + assert rec.evidence["notes"] == fit.data["notes"] + assert rec.evidence["notes"][0] == f"node b300-0 (sm103) runs the sm_100 cubin: {ia.MINOR_RULE_NOTE}" + strict = request(nodes, tmp_path, strict_arch=True) + with pytest.raises(ia.AdoptError, match="step fit failed: --strict-arch"): + adopter(strict, FakeNodes(nodes, probe=probe_out(arch_list=["sm_90", "sm_100"])), smoke=passing_smoke()).run() + + +def test_a_node_of_no_known_card_architecture_is_refused_at_fit(tmp_path): + node = b300(0, card="M890", device_family="ppu") + a = adopter(request([node], tmp_path), FakeNodes([node])) + with pytest.raises(ia.AdoptError, match="node b300-0 has M890 cards of no known architecture"): + a._fit(PINNED, ia.parse_probe(probe_out()), "miles") + + +def test_fit_refuses_another_cpu_a_missing_engine_and_a_cpu_only_torch(tmp_path): + node = b300(0) + req = request([node], tmp_path) + arm = ia.parse_probe(probe_out(uname_m="aarch64")) + assert ia.fit_problems(req, PINNED, arm, "miles")[0] == ["the image is aarch64; node b300-0 is x86_64"] + bare = ia.parse_probe(probe_out(packages={"torch": "2.9.1"})) + assert "the image has no trainer engine miles" in ia.fit_problems(req, PINNED, bare, "miles")[0][0] + cpu = ia.parse_probe(probe_out(cuda=None)) + assert "has no CUDA build" in ia.fit_problems(req, PINNED, cpu, "miles")[0][0] + vllm = request([node], tmp_path, role="sampler") + assert "the image has no sampler engine vllm" in ia.fit_problems(vllm, PINNED, bare, "vllm")[0][0] + + +def test_the_trainer_floor_still_applies_to_a_known_trainer_image(tmp_path): + a100 = b300(0, card="A100-80GB", hbm_gib=80.0) + ref = "ghcr.io/owner/yeto-miles-k31@sha256:" + "ab" * 32 + facts = ia.parse_probe(probe_out(arch_list=["sm_80", "sm_90"])) + problems, _, _ = ia.fit_problems(request([a100], tmp_path), ref, facts, "miles") + assert len(problems) == 1 and "node b300-0: trainer image" in problems[0] and "sm90+" in problems[0] + lifted = dataclasses.replace(request([a100], tmp_path), attention_backend="flash") + problems, warnings, _ = ia.fit_problems(lifted, ref, facts, "miles") + assert problems == [] and "the flash attention backend takes another path" in warnings[0] + + +def test_a_catalog_sampler_image_is_held_to_its_record(tmp_path): + from yeto.rl import sampler_pins as pins + + ref = pins.VLLM_SAMPLER_IMAGE_ROCM.removeprefix("docker:") + facts = ia.parse_probe(probe_out(packages={"vllm": "0.19"})) + problems, _, _ = ia.fit_problems(request([b300(0)], tmp_path, role="sampler"), ref, facts, "vllm") + assert len(problems) == 1 and "it is a rocm image" in problems[0] + + +# -- step 4: pull --------------------------------------------------------------------- + + +def test_a_node_short_of_image_room_stops_the_pull_everywhere(tmp_path, catalog_before): + nodes = [b300(i) for i in range(3)] + low = Behavior(host={"disk": (0, "\n".join([disk_line("/", 80, 200, dev="/dev/sda2", mount="/"), + disk_line("/var/lib/containerd", 40, mount="/"), + disk_line("/mnt/nvme/docker", 3000, mount="/mnt/nvme")]))}) + ops = FakeNodes(nodes, **{"b300-2": low}) + a = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()) + with pytest.raises(ia.AdoptError) as error: + a.run() + assert error.value.step == "pull" + assert "node b300-2: disk_images: /var/lib/containerd (containerd image store) on /: 40 GiB free" \ + in error.value.reason + assert "node b300-0:" not in error.value.reason + assert "the image stays pulled on b300-0 (a retry reuses it" in error.value.reason # the probe pulled it + assert error.value.holding == ("b300-0",) + assert "docker pull" not in ops.kinds() # no node pulled + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +def test_a_failed_pull_names_the_node(tmp_path, catalog_before): + nodes = [b300(i) for i in range(3)] + bad = Behavior(pull=(1, "Error response from daemon: no space left on device")) + ops = FakeNodes(nodes, **{"b300-2": bad}) + with pytest.raises(ia.AdoptError, match=r"step pull failed: node b300-2: image_pull: docker pull failed \(rc 1\)") \ + as error: + adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert error.value.holding == ("b300-0", "b300-1") # the probe node, then the nodes whose pull passed + assert f"the image stays pulled on b300-0, b300-1 (a retry reuses it; `docker rmi {PINNED}` there frees the " \ + "room)" in error.value.reason + assert ops.kinds().count("docker pull") == 3 # every node was pulled in parallel + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +def test_an_unreachable_node_stops_the_pull(tmp_path): + nodes = [b300(i) for i in range(2)] + ops = FakeNodes(nodes, **{"b300-1": Behavior(ssh_rc=255)}) + with pytest.raises(ia.AdoptError, match="node b300-1: ssh: ssh ops@b300-1 failed"): + adopter(request(nodes, tmp_path, node="b300-0"), ops, smoke=passing_smoke()).run() + + +# -- the whole run ---------------------------------------------------------------------- + + +def test_every_step_passes_and_the_catalog_gets_the_record(tmp_path): + nodes = [b300(i) for i in range(2)] + ops = FakeNodes(nodes) + calls = [] + report = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke(calls)).run() + assert [s.name for s in report.steps] == list(ia.STEPS) and report.ok + assert calls == [(PINNED, "miles")] + (rec,) = si.load(tmp_path / "site-images.yaml") + assert (rec.ref, rec.role, rec.engine, rec.cpu_arch, rec.card_archs, rec.device_family, rec.status) == ( + PINNED, "trainer", "miles", "x86_64", ("sm103",), "cuda", "verified-smoke") + assert rec.model == "moonshotai/Kimi-K3.1-Pro" and rec.versions["torch"] == "2.9.1+cu130" + assert rec.evidence["node"] == "b300-0" and rec.evidence["result"] == "pass" + assert rec.evidence["pulled"] == ["b300-0", "b300-1"] and rec.evidence["smoke"] == {"layers": 4} + assert set(rec.evidence["steps"]) == set(ia.STEPS) + assert si.match("kimi_k31", "trainer", nodes, path=tmp_path / "site-images.yaml") == [rec] + assert any("recorded" in line for line in report.lines()) + + +def test_a_failed_smoke_writes_nothing(tmp_path, catalog_before): + nodes = [b300(0)] + + def smoke(adopter, ref, facts, engine): + return ia.StepResult("smoke", False, "hot reload: the engine answered 500", 2.0) + + with pytest.raises(ia.AdoptError, match="step smoke failed: hot reload") as error: + adopter_ = adopter(request(nodes, tmp_path, role="sampler"), FakeNodes( + nodes, probe=probe_out(packages={"vllm": "0.19.0"})), smoke=smoke) + adopter_.run() + assert error.value.holding == ("b300-0",) and "the image stays pulled on b300-0" in error.value.reason + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +def test_no_smoke_wired_writes_nothing(tmp_path, catalog_before): + nodes = [b300(0)] + with pytest.raises(ia.AdoptError, match="step smoke failed: no trainer smoke"): + adopter(request(nodes, tmp_path), FakeNodes(nodes)).run() + assert catalog_before.read_text() == "version: 1\nimages: []\n" + + +def test_the_sampler_engine_comes_from_the_image_unless_named(tmp_path): + req = request([b300(0)], tmp_path, role="sampler") + assert ia.default_engine(req, ia.parse_probe(probe_out(packages={"sglang": "0.5"}))) == "sglang" + assert ia.default_engine(req, ia.parse_probe(probe_out(packages={"vllm": "0.19", "vllm-ascend": "0.19"}))) \ + == "vllm-ascend" + assert ia.default_engine(dataclasses.replace(req, engine="SGLang"), None) == "sglang" + assert ia.default_engine(request([b300(0)], tmp_path), None) == "miles" + + +def test_role_nodes_take_spares_and_unroled_nodes(): + nodes = [b300(0, roles=("trainer",)), b300(1, roles=("trainer-spare",)), b300(2, roles=("sampler",)), b300(3)] + assert [n.name for n in ia.role_nodes(nodes, "trainer")] == ["b300-0", "b300-1", "b300-3"] + assert [n.name for n in ia.role_nodes(nodes, "sampler")] == ["b300-2", "b300-3"] + with pytest.raises(ValueError, match="--node b300-9 is not a trainer node"): + ia.AdoptRequest(ref=PINNED, model="m", role="trainer", nodes=tuple(nodes), node="b300-9") + + +def test_an_image_whose_probe_saw_no_card_architecture_is_refused(): + facts = ia.parse_probe(probe_out(arch_list=[])) + assert ia.card_arch_problem(facts, b300(0)).startswith("the probe read no card architecture from the image") + + +def test_a_tag_behind_the_token_flow_is_pinned_from_the_authenticated_answer(): + def urlopen(req, timeout=None): + if "/token?" in req.full_url: + return _Resp(200, body=b'{"token": "t0k"}') + if req.headers.get("Authorization") == "Bearer t0k": + return _Resp(200, {"Docker-Content-Digest": DIGEST}) + raise urllib.error.HTTPError(req.full_url, 401, "x", {"WWW-Authenticate": ( + 'Bearer realm="https://reg.example/token",service="reg.example",scope="repository:site/miles-new:pull"')}, + None) + assert ia.pin(TAGGED, urlopen=urlopen) == PINNED + + +def test_the_preflight_pull_reports_a_failed_pull(): + from yeto.launch.preflight import cluster as cp + + nodes = [b300(i) for i in range(2)] + ops = FakeNodes(nodes, **{"b300-1": Behavior(pull=(1, "Error response from daemon: manifest unknown"))}) + pf = cp.ClusterPreflight(nodes, image=PINNED, ops=ops, log=lambda m: None, clock=lambda: FakeCluster.NOW) + checks, pulled = pf.pull() + assert pulled is False and {c.scope for c in checks if c.name == "image_pull" and c.status == cp.FAIL} == {"b300-1"} + ok_ops = FakeNodes(nodes) + assert cp.ClusterPreflight(nodes, image=PINNED, ops=ok_ops, log=lambda m: None, + clock=lambda: FakeCluster.NOW).pull()[1] is True + + +# -- the probe node's checks (host, idle cards) and the probe fallback ---------------------- + + +def test_the_probe_node_is_checked_for_room_before_the_probe_pulls(tmp_path, catalog_before): + nodes = [b300(i) for i in range(2)] + low = Behavior(host={"disk": (0, "\n".join([disk_line("/", 80, 200, dev="/dev/sda2", mount="/"), + disk_line("/var/lib/containerd", 40, mount="/")]))}) + ops = FakeNodes(nodes, **{"b300-0": low}) + with pytest.raises(ia.AdoptError, match=r"step probe failed: node b300-0: disk_images: ") as error: + adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert error.value.holding == () and "stays pulled" not in error.value.reason + assert ops.kinds() == ["date", "host"] # no probe ran + + +@pytest.mark.parametrize("family, card, out, apps", [ + ("cuda", "B300", "YETO_BUSY tool cuda\nYETO_BUSY apps 4242, python3, 81000 MiB\n", ["4242 python3"]), + ("cuda", "B300", "YETO_BUSY tool cuda\nYETO_BUSY apps No devices were found\n", []), + ("npu", "910B3", "YETO_BUSY tool ascend\n" + "YETO_BUSY apps | 0 910B3 | OK | 93.1 39 0 / 0 |\n" + "YETO_BUSY apps | 0 | 0000:C1:00.0 | 0 0 / 0 3404 / 65536 |\n" + "YETO_BUSY apps | 0 0 | 2938420 | python | 61307 |\n" + "YETO_BUSY apps | No running processes found in NPU 1 |\n", ["2938420 python"]), + ("rocm", "MI355X", "YETO_BUSY tool rocm\nYETO_BUSY apps gpu,name,pid,mem\nYETO_BUSY apps 0,vllm,777,1024\n", + ["777 vllm"]), + ("rocm", "MI355X", "YETO_BUSY tool rocm\nYETO_BUSY apps KFD process information:\n" + "YETO_BUSY apps PID PROCESS NAME GPU(s) VRAM USED\nYETO_BUSY apps 3131 python3 1 0\n", ["3131 python3"]), +]) +def test_busy_parsing_per_family(family, card, out, apps): + from yeto.launch.node_inventory import profile_of + + node = b300(0, card=card, device_family=family) + found, containers, readable = ia.parse_busy(out, profile_of(node).family) + assert (found, containers, readable) == (apps, [], True) + assert ia.BUSY_MARK in ia.busy_script(node) + + +def test_the_busy_script_runs_under_bash(tmp_path): + done = subprocess.run(["bash", "-c", ia.busy_script(b300(0))], capture_output=True, text=True, timeout=60, + env={"PATH": "/usr/bin:/bin"}) + assert ia.parse_busy(done.stdout, "cuda")[2] is False # no nvidia-smi here: unreadable, not busy + assert f"{ia.BUSY_MARK} tool none" in done.stdout + + +def test_a_busy_probe_node_is_refused_unless_allowed(tmp_path, catalog_before): + nodes = [b300(0)] + busy = "YETO_BUSY tool cuda\nYETO_BUSY apps 4242, python3, 81000 MiB\nYETO_BUSY containers yeto-r1-i0 img\n" + with pytest.raises(ia.AdoptError, match=r"step probe failed: node b300-0 is in use: process 4242 python3, " + r"container yeto-r1-i0 img; .* --allow-busy"): + adopter(request(nodes, tmp_path), FakeNodes(nodes, busy=busy), smoke=passing_smoke()).run() + assert catalog_before.read_text() == "version: 1\nimages: []\n" + logs = [] + a = adopter(request(nodes, tmp_path, allow_busy=True), FakeNodes(nodes, busy=busy), smoke=passing_smoke()) + a.log = logs.append + assert a.run().ok + assert any("WARNING: node b300-0 is in use" in m and "--allow-busy" in m for m in logs) + + +def test_an_unreadable_card_tool_warns_and_goes_on(tmp_path): + nodes = [b300(0)] + logs = [] + a = adopter(request(nodes, tmp_path), FakeNodes(nodes, busy="YETO_BUSY tool none\n"), smoke=passing_smoke()) + a.log = logs.append + assert a.run().ok and any("no card tool to read its processes" in m for m in logs) + + +def test_the_probe_falls_back_to_the_cards_when_the_build_flags_are_empty(tmp_path): + nodes = [b300(0)] + ops = FakeNodes(nodes, bare=probe_out(arch_list=[])) + report = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert ops.kinds()[:5] == ["date", "host", "busy", "probe", "probe+cards"] + assert report.facts.arch_list == ("sm_90", "sm_100", "sm_103", "compute_103") + flags = FakeNodes(nodes) + adopter(request(nodes, tmp_path), flags, smoke=passing_smoke()).run() + assert "probe+cards" not in flags.kinds() # the build flags were enough + + +def _podman(i, **kw): + from yeto.launch.node_inventory import NodeProfile + + return NodeProfile.from_node(b300(i, docker_args=(), **kw), container="podman") + + +def _graphroot(root="/mnt/nvme/podman", free=3000): + """A podman node's host probe: ``podman info`` names ``root``, which has ``free`` GiB.""" + return Behavior(host={"podman_root": (0, root), + "disk": (0, "\n".join([disk_line("/", 80, 200, dev="/dev/sda2", mount="/"), + disk_line(root, free, mount="/mnt/nvme")]))}) + + +def test_podman_nodes_are_probed_checked_and_pulled_with_podman(tmp_path): + nodes = [_podman(0, runtime="rootfs"), b300(1)] # podman on a node of no docker runtime + ops = FakeNodes(nodes, **{"b300-0": _graphroot()}) + report = adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert report.ok + pulls = sorted(s.split(" pull")[0] + "@" + n for n, s in ops.scripts if " pull -q " in s) + assert pulls == ["docker@b300-1", "podman@b300-0"] # each node with its own engine + host = [s for n, s in ops.scripts if n == "b300-0" and "@@yeto-section" in s] + assert host and all("podman info --format" in s for s in host) + assert not any("podman" in s for n, s in ops.scripts if n == "b300-1" and "@@yeto-section" in s) + (rec,) = si.load(tmp_path / "site-images.yaml") + assert rec.evidence["pulled"] == ["b300-0", "b300-1"] + + +def test_a_podman_graphroot_short_of_room_stops_the_pull(tmp_path): + nodes = [_podman(0), _podman(1)] + low = Behavior(host={"podman_root": (0, "/var/lib/containers/storage"), + "disk": (0, "\n".join([disk_line("/", 80, 200, dev="/dev/sda2", mount="/"), + disk_line("/var/lib/containers/storage", 30, mount="/")]))}) + ops = FakeNodes(nodes, **{"b300-0": _graphroot(), "b300-1": low}) + with pytest.raises(ia.AdoptError) as error: + adopter(request(nodes, tmp_path, node="b300-0"), ops, smoke=passing_smoke()).run() + assert error.value.step == "pull" + assert ("node b300-1: disk_images: /var/lib/containers/storage (podman graphroot) on /: 30 GiB free " + "(move it to NVMe (graphroot in /etc/containers/storage.conf))") in error.value.reason + assert not any(" pull -q " in s for _, s in ops.scripts) + + +def test_the_pull_needs_a_container_engine(tmp_path): + nodes = [b300(i, runtime="rootfs") for i in range(2)] + a = adopter(request(nodes, tmp_path), FakeNodes(nodes)) + with pytest.raises(ia.AdoptError, match=r"step pull failed: no trainer node runs a container engine " + r"\(docker or podman\): \['b300-0', 'b300-1'\]"): + a._pull(PINNED) + + +def test_the_preflight_host_probe_of_a_docker_node_is_unchanged(): + from yeto.launch.preflight import cluster as cp + + node = b300(0) + assert cp.host_sections(node) == cp.host_sections(node, engine="docker") + assert "podman" not in str(cp.host_sections(node)) and "podman" in str(cp.host_sections(node, engine="podman")) + assert [n for n, _ in cp.host_sections(node, engine="podman")][-2:] == ["podman_root", "disk"] + + +def test_a_fit_failure_names_the_probe_node_that_holds_the_image(tmp_path): + nodes = [b300(0)] + ops = FakeNodes(nodes, probe=probe_out(uname_m="aarch64")) + with pytest.raises(ia.AdoptError, match="step fit failed") as error: + adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert error.value.holding == ("b300-0",) + + +def test_a_tag_next_to_a_digest_is_left_out_of_the_repository_and_the_token_scope(): + assert im.split_tagged_ref(f"reg.example/org/img:v1@{DIGEST}") == ("reg.example", "org/img", DIGEST) + assert im.split_tagged_ref(f"reg.example:5000/org/img:v1@{DIGEST}") == ("reg.example:5000", "org/img", DIGEST) + seen = [] + + def urlopen(req, timeout=None): # a registry: the challenge's scope is the repository the URL names + seen.append(req.full_url) + if "/token?" in req.full_url: + query = urllib.parse.parse_qs(urllib.parse.urlsplit(req.full_url).query) + ok = query.get("scope") == ["repository:org/img:pull"] + return _Resp(200, body=b'{"token": "t0k"}' if ok else b'{"token": "wrong-scope"}') + if req.headers.get("Authorization") == "Bearer t0k": + return _Resp(200, {"Docker-Content-Digest": DIGEST}) + repo = req.full_url.split("/v2/", 1)[1].rsplit("/manifests/", 1)[0] + raise urllib.error.HTTPError(req.full_url, 401, "x", {"WWW-Authenticate": ( + f'Bearer realm="https://reg.example/token",service="reg.example",scope="repository:{repo}:pull"')}, None) + assert ia.pin(f"reg.example/org/img:v1@{DIGEST}", urlopen=urlopen) == f"reg.example/org/img@{DIGEST}" + assert seen[0] == f"https://reg.example/v2/org/img/manifests/{DIGEST}" + + +@pytest.mark.parametrize("root, why", [ + ("", "`podman info` printed no storage graphroot"), + ("/srv/containers", "the graphroot /srv/containers that `podman info` printed is not on the node"), +]) +def test_an_image_store_whose_disk_cannot_be_confirmed_fails(tmp_path, root, why): + nodes = [_podman(0)] + ops = FakeNodes(nodes, **{"b300-0": Behavior(host={"podman_root": (0, root)})}) + with pytest.raises(ia.AdoptError) as error: + adopter(request(nodes, tmp_path), ops, smoke=passing_smoke()).run() + assert error.value.step == "probe" + assert f"disk_images: cannot confirm the disk of the image store: {why}" in error.value.reason + assert ops.kinds()[-1] == "host" # stopped before the probe ran the image + + +def test_a_sudo_pool_engine_reads_its_rootful_store_and_pulls_through_sudo(tmp_path): + class Raw(FakeNodes): + def run(self, node, script, *, timeout=300.0): + self.raw = [*getattr(self, "raw", []), script] + return super().run(node, script, timeout=timeout) + + nodes = [_podman(0), _podman(1)] + ops = Raw(nodes, **{n.name: _graphroot() for n in nodes}) + report = adopter(request(nodes, tmp_path, container_sudo=True), ops, smoke=passing_smoke()).run() + assert report.ok + sent = [s for s in ops.raw if ia.FACT in s or ia.BUSY_MARK in s] + assert sent and all(s.startswith("sudo -n podman run ") for s in sent if ia.FACT in s) + assert all("sudo -n podman ps --filter name=^yeto-" in s for s in sent if ia.BUSY_MARK in s) + host = [s for _, s in ops.scripts if "@@yeto-section" in s] + assert host and all("sudo -n podman info --format '{{.Store.GraphRoot}}'" in s for s in host) + assert all(s.count("podman info") == s.count("sudo -n podman info") == 2 for s in host) # section and disk + assert sorted(n for n, s in ops.scripts if s.startswith("sudo -n podman pull -q ")) == ["b300-0", "b300-1"] + assert shlex.split(ia.probe_script(PINNED, nodes[0], sudo=True))[:4] == ["sudo", "-n", "podman", "run"] + assert "sudo -n podman ps --filter name=^yeto-" in ia.busy_script(nodes[0], sudo=True) + assert "sudo" not in ia.probe_script(PINNED, nodes[0]) and "sudo" not in ia.busy_script(nodes[0]) + + +def test_a_docker_node_with_sudo_reads_docker_info_through_sudo_and_without_it_is_unchanged(): + from yeto.launch.preflight import cluster as cp + + node = b300(0) + plain = dict(cp.host_sections(node)) + sudo = dict(cp.host_sections(node, sudo=True)) + assert plain == dict(cp.host_sections(node, engine="docker", sudo=False)) and "sudo" not in str(plain) + assert sudo["docker"] == "sudo -n docker info --format '{{json .}}'" + assert "$(sudo -n docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)" in sudo["disk"] + assert {k: v for k, v in sudo.items() if k not in ("docker", "disk")} == \ + {k: v for k, v in plain.items() if k not in ("docker", "disk")} + + +def test_the_docker_host_probe_is_byte_for_byte_main_s(): + """The preflight's host probe of a docker node (no engine, no sudo given): the digest + of main's script (recorded from main d9fb37915), so the customer path cannot drift.""" + import hashlib + + from yeto.launch.preflight import cluster as cp + + for node, want in ((b300(0), "3e692f2760ba7ad24840de395a33dd4b106b8abcc3fe645004aad4a2b52fcd8e"), + (b300(1, mounts={"/mnt/nvme/x": "/x"}), + "958b24e9b3fed68eeb27d8221ae0357653a5009b8e016a3a9ba270211cfce5de")): + assert hashlib.sha256(cp.probe_script(cp.host_sections(node)).encode()).hexdigest() == want diff --git a/tests/test_run_flags.py b/tests/test_run_flags.py index 19036f788..677df16f0 100644 --- a/tests/test_run_flags.py +++ b/tests/test_run_flags.py @@ -261,6 +261,8 @@ def test_forward_tables_name_flags_of_both_layers(): # flags: syncer, docker, git, pip, ray, torchrun, sky, ... Pinned so that an island # flag renamed in the schema but still spelled the old way in the launcher fails. _NON_RL_LITERALS = frozenset({ + # yeto image adopt (yeto.launch.image_adopt): its flags, and the card tools / docker ps of its idle check + "--role", "--strict-arch", "--allow-busy", "--showpids", "--csv", "--filter", # podman / docker CLI flags of the own-SSH-node sampler pool (yeto.launch.ssh_sampler_pool) "--security-opt", "--signal", "--tail", "--type", # the AgentENV-side regctl setting the task image check names (yeto.launch.agentic_setup) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index d1b44ee70..ef6001c80 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -675,3 +675,21 @@ def test_the_kept_file_is_written_through_a_temporary_file_of_its_own(tmp_path, ops.images_path().with_suffix(".tmp").mkdir(parents=True) # another writer's fixed temporary path assert ops.image_for(ops.conf.nodes[0]) == REF3 assert json.loads(ops.images_path().read_text())["images"]["b300-0"]["ref"] == REF3 + + +def test_a_spare_naming_its_own_image_does_not_turn_the_catalog_off(tmp_path, capsys): + from yeto.launch.rl_backend import resolve_default_rl_image + + inv = _inventory(tmp_path, catalog=write_catalog(tmp_path / "c.yaml", record()), nodes=2) + doc = yaml.safe_load(inv.read_text()) + doc["nodes"][0]["roles"] = ["trainer"] + doc["nodes"][1].update(roles=["trainer-spare"], image="registry.example/site/spare@sha256:" + "e" * 64) + inv.write_text(yaml.safe_dump(doc)) + args = _args(inv) + resolve_default_rl_image(args) + assert args.rl_image == "docker:" + record()["ref"] # the island's node names no image: the site record + doc["nodes"][0]["image"] = doc["nodes"][1].pop("image") # the island's own node names one: no catalog + inv.write_text(yaml.safe_dump(doc)) + args = _args(inv) + resolve_default_rl_image(args) + assert args.rl_image != "docker:" + record()["ref"] diff --git a/yeto/launch/image_adopt.py b/yeto/launch/image_adopt.py new file mode 100644 index 000000000..db98da2d0 --- /dev/null +++ b/yeto/launch/image_adopt.py @@ -0,0 +1,784 @@ +"""``yeto image adopt``: take an image built for one model into the site image catalog. + +An operator who has an image optimized for a new model (a trainer image for a Miles +or verl island, a sampler image for a vLLM / SGLang pool) adopts it on an SSH node +inventory in five steps, each one an existing module of yeto: + +1. **manifest**: the registry has the image (:mod:`.image_manifest`, a manifest HEAD + with the registry login of the pull); a tag is pinned to its digest. Nothing is + asked of a node before this step passed; +2. **probe**: one node, after its host checks (ssh, the host probe, room in its image + root) and a check that its cards are idle (:func:`busy_script`), runs the image once + (`` run --rm``, no cards: the built card architectures are read + from torch's build flags) and prints what it carries: CPU architecture, Python, + torch, CUDA / HIP, the card architectures its kernels were built for, the engine + packages and the yeto image lock (``/opt/yeto/image``); +3. **fit**: the image against every node of the role: CPU architecture, device + runtime, card architecture (the image's built architectures under the CUDA binary + compatibility rules, :func:`card_arch_fit`; a trainer image's + verified floor, :mod:`.trainer_image_check`; a catalog sampler image's record, + :func:`.engine_images.image_mismatch`) and the engine the role runs; +4. **pull**: every node of the role pulls the image in parallel after its image root + was checked for room (the cluster preflight's ssh, host probe, ``disk_images`` and + ``image_pull`` checks, :meth:`.preflight.cluster.ClusterPreflight.pull`; a failed + pull names the node and docker's line, :mod:`.image_pull`); +5. **smoke**: the role's smoke on one node (:mod:`.image_smoke`). + +Every step that fails stops the adoption with its name and the reason +(:class:`AdoptError`, which names the nodes the image was already pulled on: it stays +there for a retry); the catalog is written only after the smoke passed, with the +versions the probe read and the evidence of the run (:mod:`.site_images`). +""" + +from __future__ import annotations + +import datetime +import json +import re +import shlex +import sys +import time +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from . import engine_images, image_manifest, image_pull, site_images, trainer_image_check +from .node_inventory import Node, card_arch_of + +STEPS = ("manifest", "probe", "fit", "pull", "smoke") +FACT = "YETO_IMAGE_FACT" +LOCK_PATH = "/opt/yeto/image/versions.lock.json" +# interpreters a probe tries in the image, in order (the sampler images' own venvs first) +PYTHONS = ("/opt/runtime-venv/bin/python3", "/opt/sglang/bin/python3", "python3", "python") +# the packages a probe reads (importlib.metadata names) +PACKAGES = ("torch", "vllm", "vllm-ascend", "sglang", "miles", "megatron-core", "megatron-bridge", + "transformer-engine", "verl", "flash-attn", "torch-npu", "ray", "transformers") +# the packages a role's engine needs in the image (any of them) +ENGINE_PACKAGES = {("trainer", "miles"): ("miles", "megatron-core"), ("trainer", "verl"): ("verl",), + ("sampler", "vllm"): ("vllm",), ("sampler", "sglang"): ("sglang",), + ("sampler", "vllm-ascend"): ("vllm-ascend",)} +PROBE_TIMEOUT_S = 3600.0 # the probe node pulls the image first +BUSY_MARK = "YETO_BUSY" +MINOR_RULE_NOTE = "compatible by CUDA minor-version rule; the smoke test is the final check" +PTX_RULE_NOTE = "compatible by PTX JIT; the smoke test is the final check" +CUDA_RULE = ("CUDA binary compatibility: a cubin sm_XY runs on compute capability X.Z with Z >= Y, sm_XYa only " + "on exactly X.Y; PTX compute_XY is JIT-compiled on any X.Y or newer card, compute_XYa only on X.Y") + + +class AdoptError(RuntimeError): + """An adoption step failed; ``step`` is one of :data:`STEPS`.""" + + def __init__(self, step: str, reason: str, *, holding: Sequence[str] = ()): + super().__init__(f"image adopt: step {step} failed: {reason}") + self.step = step + self.reason = reason + self.holding = tuple(holding) + + +@dataclass(frozen=True) +class AdoptRequest: + """What to adopt: ``ref`` (a tag or a digest), the ``model`` it is built for, the + ``role`` (``trainer`` / ``sampler``), the inventory nodes (:func:`role_nodes`), + the ``engine`` (trainer: the ``--rl-backend``; sampler: ``vllm`` / ``sglang`` / + ``vllm-ascend``; None: the default backend, or the engine the probe finds), the node + that probes and smokes (None: the first of the role), the catalog path (None: the + default), the image root's free space a pull needs, the trainer's attention + backend (the trainer floor of :mod:`.trainer_image_check`), ``strict_arch`` (the + image must carry a cubin of exactly the node's card architecture: no minor-version + or PTX compatibility), ``allow_busy`` (probe and smoke a node whose cards run + something, with a warning) and ``container_sudo`` (the engine runs as ``sudo -n + ``, as an ssh sampler pool's ``container.sudo`` runs it: its rootful store is + the one checked, pulled into and run from).""" + + ref: str + model: str + role: str + nodes: tuple[Node, ...] + engine: str | None = None + node: str | None = None + catalog: str | None = None + min_image_free_gib: float = 120.0 + attention_backend: str = "auto" + strict_arch: bool = False + allow_busy: bool = False + container_sudo: bool = False + + def __post_init__(self) -> None: + if self.role not in site_images.ROLES: + raise ValueError(f"--role {self.role!r} is unknown (known: {list(site_images.ROLES)})") + if not self.nodes: + raise ValueError(f"the inventory has no {self.role} node") + if self.node is not None and self.node not in {n.name for n in self.nodes}: + raise ValueError(f"--node {self.node} is not a {self.role} node of the inventory " + f"({[n.name for n in self.nodes]})") + + @property + def probe_node(self) -> Node: + return next(n for n in self.nodes if self.node in (None, n.name)) + + +@dataclass(frozen=True) +class ImageFacts: + """What the probe read inside the image.""" + + cpu_arch: str | None + python: str | None + python_path: str | None + torch: str | None + cuda: str | None + hip: str | None + arch_list: tuple[str, ...] + packages: Mapping[str, str] + lock: Mapping[str, Any] | None = None + arch_source: str | None = None # "build_flags" (no card needed) / "cards" + + def versions(self) -> dict[str, str]: + """The catalog record's ``versions``: the interpreter, torch, the device runtime and + every package found.""" + out = {"python": self.python, "python_path": self.python_path, "torch": self.torch, "cuda": self.cuda, + "hip": self.hip, **{k: v for k, v in self.packages.items() if k != "torch"}} + if self.lock: + out["image_lock"] = str(self.lock.get("image") or self.lock.get("name") or "present") + return {k: str(v) for k, v in out.items() if v} + + +@dataclass +class StepResult: + name: str + ok: bool + detail: str + seconds: float + data: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class AdoptReport: + """The steps run so far; ``record`` once the catalog was written.""" + + request: AdoptRequest + steps: list[StepResult] = field(default_factory=list) + pinned: str | None = None + facts: ImageFacts | None = None + record: site_images.SiteImage | None = None + catalog: Path | None = None + + @property + def ok(self) -> bool: + return bool(self.steps) and all(s.ok for s in self.steps) + + def lines(self) -> list[str]: + out = [f"[image adopt] {s.name}: {'ok' if s.ok else 'FAILED'} ({s.seconds:.1f} s) {s.detail}" + for s in self.steps] + if self.record is not None: + out.append(f"[image adopt] recorded {self.record.ref} for {self.record.model} {self.record.role} " + f"({self.record.engine}, {'/'.join(self.record.card_archs)}) in {self.catalog}") + return out + + +def role_nodes(nodes: Sequence[Node], role: str) -> list[Node]: + """The inventory nodes of ``role``: no roles, the role itself, or a role of its kind + (``trainer-spare``): every node that may run the image is pulled and checked.""" + return [n for n in nodes if not n.roles or any(r == role or r.startswith(role + "-") for r in n.roles)] + + +# --- step 1: manifest ---------------------------------------------------------------- + + +def pin(ref: str, *, login: Mapping[str, str] | None = None, urlopen=None) -> str: + """The digest-pinned reference of ``ref`` (no ``docker:`` prefix), or :class:`AdoptError` + (step ``manifest``) when the registry has no such manifest or cannot be read. With + ``YETO_IMAGE_MANIFEST_CHECK=off`` a digest is taken as it is and a tag is refused.""" + bare = ref.strip().removeprefix("docker:") + if not image_manifest.enabled(): + if not re.search(r"@sha256:[0-9a-f]{64}$", bare): + raise AdoptError("manifest", f"{image_manifest.CHECK_ENV}=off: a tag cannot be pinned; give the " + "image's digest (REGISTRY/IMAGE@sha256:<64 hex>)") + return bare + try: + status, detail = image_manifest.pin_digest(bare, dict(login) if login else None, urlopen=urlopen) + except ValueError as error: + raise AdoptError("manifest", str(error)) from None + if status == image_manifest.PRESENT: + return detail + if status == image_manifest.MISSING: + raise AdoptError("manifest", f"the registry has no manifest for {bare} ({detail})") + if status == image_manifest.DENIED: + raise AdoptError("manifest", f"{detail}; give the registry login of the pull (SKYPILOT_DOCKER_USERNAME / " + "SKYPILOT_DOCKER_PASSWORD / SKYPILOT_DOCKER_SERVER, or ~/.docker/config.json)") + raise AdoptError("manifest", f"{detail}; {image_manifest.CHECK_ENV}=off skips the check for a digest") + + +def registry_login(ref: str) -> dict[str, str] | None: + """The registry login a pull of ``ref`` would use (the ``SKYPILOT_DOCKER_*`` variables, + else ``~/.docker/config.json``); never printed.""" + host = image_manifest.split_tagged_ref(ref)[0] + return image_pull.fresh_registry_login(host) + + +# --- step 2: probe ------------------------------------------------------------------- + +_PROBE_PY = r""" +import json, platform, sys +from importlib import metadata +def fact(key, value): + print("YETO_IMAGE_FACT", key, json.dumps(value)) +fact("python", platform.python_version()) +fact("python_path", sys.executable) +pkgs = {} +for name in PACKAGES: + try: + pkgs[name] = metadata.version(name) + except Exception: + pass +fact("packages", pkgs) +try: + import torch + fact("torch", torch.__version__) + fact("cuda", getattr(torch.version, "cuda", None)) + fact("hip", getattr(torch.version, "hip", None)) + archs, source = [], None + try: + flags = torch._C._cuda_getArchFlags() + if flags: + archs, source = flags.replace(";", " ").split(), "build_flags" + except Exception: + pass + if not archs: + try: + archs, source = list(torch.cuda.get_arch_list()), "cards" + except Exception: + pass + fact("arch_list", archs) + fact("arch_source", source) +except Exception as error: + fact("torch_error", f"{type(error).__name__}: {error}") +""".replace("PACKAGES", repr(PACKAGES)) + + +def engine_of(node: Node) -> str | None: + """The container engine of ``node``'s images (docker / podman; None: it runs none).""" + from .node_inventory import profile_of # noqa: PLC0415 + + engine = profile_of(node).container + return engine if engine in ("docker", "podman") else None + + +def container_engine(node: Node) -> str: + """The container engine the node runs images with (its profile's ``container``: + ``docker`` / ``podman``); a node that runs no container is refused (step ``probe``).""" + from .node_inventory import profile_of # noqa: PLC0415 + + engine = profile_of(node).container + if engine not in ("docker", "podman"): + raise AdoptError("probe", f"node {node.name} runs no container engine (container {engine!r}): an image is " + "adopted on a docker or podman node") + return engine + + +def probe_script(image: str, node: Node, *, cards: bool = False, sudo: bool = False) -> str: + """The node's `` run --rm`` of ``image`` that prints the image's facts + (:data:`FACT` lines): ``uname -m``, the image lock and, under the first interpreter of + :data:`PYTHONS` that imports torch (else the first that runs), the Python facts. + The built card architectures come from torch's build flags + (``torch._C._cuda_getArchFlags``), which need no card: the container gets the + node's device flags only with ``cards`` (the fallback for a torch whose flags are + not readable; ``torch.cuda.get_arch_list`` is empty without cards).""" + from .node_inventory import profile_of # noqa: PLC0415 + + engine = container_engine(node) + devices = profile_of(node).devices(None, engine=engine).args if cards else () + inner = (f"echo {FACT} uname_m \\\"$(uname -m)\\\"; " + f"if [ -f {LOCK_PATH} ]; then printf '%s lock ' {FACT}; tr -d '\\n' < {LOCK_PATH}; echo; fi; " + "PY=; for p in " + " ".join(PYTHONS) + "; do " + "if command -v \"$p\" >/dev/null 2>&1 && \"$p\" -c 'import torch' >/dev/null 2>&1; then PY=$p; break; fi; " + "done; " + "if [ -z \"$PY\" ]; then for p in " + " ".join(PYTHONS) + "; do " + "if command -v \"$p\" >/dev/null 2>&1; then PY=$p; break; fi; done; fi; " + f"if [ -z \"$PY\" ]; then echo {FACT} no_python true; exit 0; fi; " + f"\"$PY\" -c {shlex.quote(_PROBE_PY)}") + argv = [*(["sudo", "-n"] if sudo else []), engine, "run", "--rm", "--network", "host", *devices, + "--entrypoint", "bash", image, "-c", inner] + return shlex.join(argv) + + +# the card tool that lists the processes on the cards, per unified family +_BUSY_TOOLS = { + "cuda": (("nvidia-smi",), "nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv,noheader"), + "rocm": (("amd-smi", "rocm-smi"), "if command -v amd-smi >/dev/null 2>&1; then amd-smi process --csv; " + "else rocm-smi --showpids; fi"), + "ascend": (("npu-smi",), "npu-smi info"), +} + + +def busy_script(node: Node, *, sudo: bool = False) -> str: + """What runs on the node's cards: the family's card tool (:data:`_BUSY_TOOLS`: the + compute processes of ``nvidia-smi``, ``amd-smi process`` / ``rocm-smi --showpids``, + the process rows of ``npu-smi info``) and the node's running yeto containers. Each + line of the output is tagged (``YETO_BUSY tool|apps|containers ...``).""" + from .node_inventory import profile_of # noqa: PLC0415 + + profile = profile_of(node) + found = _BUSY_TOOLS.get(profile.family) + engine = profile.container if profile.container in ("docker", "podman") else "docker" + parts = [] + if found: + names, tool = found + have = " || ".join(f"command -v {n} >/dev/null 2>&1" for n in names) + parts.append(f"if {have}; then echo {BUSY_MARK} tool {profile.family}; " + f"( {tool} ) 2>&1 | sed 's/^/{BUSY_MARK} apps /'; else echo {BUSY_MARK} tool none; fi") + else: + parts.append(f"echo {BUSY_MARK} tool none") + parts.append(f"{'sudo -n ' if sudo else ''}{engine} ps --filter name=^yeto- --format '{{{{.Names}}}} {{{{.Image}}}}' 2>/dev/null " + f"| sed 's/^/{BUSY_MARK} containers /'") + return "; ".join(parts) + + +_NPU_PROCESS_ROW = re.compile(r"^\|\s*\d+\s+\d+\s*\|\s*(\d+)\s*\|\s*(\S+)") + + +def parse_busy(text: str, family: str) -> tuple[list[str], list[str], bool]: + """``(processes, containers, readable)`` of a :func:`busy_script` output: the + processes on the cards (``pid name``), the running yeto containers and whether a + card tool was read at all.""" + apps: list[str] = [] + containers: list[str] = [] + readable = False + for line in (text or "").splitlines(): + parts = line.rstrip().split(" ", 2) + if len(parts) < 3 or parts[0] != BUSY_MARK: + continue + kind, value = parts[1], parts[2].strip() + if kind == "tool": + readable = value != "none" + elif kind == "containers" and value: + containers.append(value) + elif kind == "apps" and value: + apps += _busy_rows(value, family) + return apps, containers, readable + + +def _busy_rows(line: str, family: str) -> list[str]: + if family == "cuda": # pid, process_name, used_memory + cells = [c.strip() for c in line.split(",")] + return [f"{cells[0]} {cells[1] if len(cells) > 1 else '?'}"] if cells[0].isdigit() else [] + if family == "ascend": + m = _NPU_PROCESS_ROW.match(line) + return [f"{m.group(1)} {m.group(2)}"] if m else [] + if family == "rocm": # amd-smi process --csv: gpu,name,pid,...; rocm-smi --showpids: PID NAME GPU(s) ... + cells = [c.strip() for c in line.split(",")] + if len(cells) >= 3 and cells[0].isdigit() and cells[2].isdigit(): + return [f"{cells[2]} {cells[1]}"] + words = line.split() + return [f"{words[0]} {words[1]}"] if len(words) >= 2 and words[0].isdigit() and len(cells) == 1 else [] + return [] + + +def parse_probe(text: str) -> ImageFacts: + """The facts of a probe's output; a line that does not parse is skipped.""" + facts: dict[str, Any] = {} + for line in (text or "").splitlines(): + parts = line.strip().split(" ", 2) + if len(parts) != 3 or parts[0] != FACT: + continue + try: + facts[parts[1]] = json.loads(parts[2]) + except ValueError: + continue + cpu = facts.get("uname_m") + try: + cpu = engine_images.canonical_cpu_arch(cpu) if cpu else None + except engine_images.UnknownCpuArch: + pass + packages = facts.get("packages") if isinstance(facts.get("packages"), dict) else {} + archs = facts.get("arch_list") if isinstance(facts.get("arch_list"), list) else [] + source = facts.get("arch_source") if isinstance(facts.get("arch_source"), str) else None + lock = facts.get("lock") if isinstance(facts.get("lock"), dict) else None + return ImageFacts(cpu_arch=cpu, python=facts.get("python"), python_path=facts.get("python_path"), + torch=facts.get("torch"), cuda=facts.get("cuda"), hip=facts.get("hip"), + arch_list=tuple(str(a).lower() for a in archs), + packages={str(k): str(v) for k, v in packages.items()}, lock=lock, arch_source=source) + + +# --- step 3: fit --------------------------------------------------------------------- + + +_CUDA_ARCH = re.compile(r"(sm|compute)_?(\d{2,3})([af]?)") + + +def _cc(arch: str) -> tuple[str, tuple[int, int], str] | None: + """``(kind, (major, minor), suffix)`` of ``sm_103`` / ``sm103`` / ``compute_90a``.""" + m = _CUDA_ARCH.fullmatch(arch) + if not m: + return None + digits = m.group(2) + return m.group(1), (int(digits[:-1]), int(digits[-1])), m.group(3) + + +def _gfx(arch: str) -> str: + """A ROCm target without its feature suffix (``gfx90a:sramecc+:xnack-`` -> ``gfx90a``).""" + return arch.split(":", 1)[0] + + +def node_card_arch(node: Node) -> str | None: + """The node's card architecture: its profile's ``card_arch`` (an inventory may set + it), else the catalog's for its card.""" + from .node_inventory import profile_of # noqa: PLC0415 + + arch = profile_of(node).card_arch or card_arch_of(node.card) + return str(arch).lower() if arch else None + + +def card_arch_fit(facts: ImageFacts, node: Node, *, strict: bool = False) -> tuple[str | None, str | None]: + """``(problem, note)`` of the image's built card architectures on ``node``'s cards + (problem None: they serve them, or the node's architecture is unknown; note: how). + + CUDA, the binary compatibility rules (:data:`CUDA_RULE`): a cubin of exactly the + node's ``sm_XY`` serves it; otherwise a cubin ``sm_XW`` (no ``a`` suffix) of the same + major with W <= the node's minor (note :data:`MINOR_RULE_NOTE`), or a PTX + ``compute_XY`` the node's capability reaches (``compute_XYa``: only exactly X.Y; + note :data:`PTX_RULE_NOTE`). With ``strict`` only the exact cubin counts. ROCm: + the node's ``gfx`` target is built (feature suffixes after ``:`` ignored). An image + whose probe saw no architecture is refused: nothing says it runs there.""" + arch = node_card_arch(node) + if not arch: + return None, None + built = facts.arch_list + have = f"{node.card} ({arch})" + if not built: + return (f"the probe read no card architecture from the image (torch's build flags and " + f"torch.cuda.get_arch_list() are empty: no device build of torch); node {node.name} has {have}"), None + node_cc = _cc(arch) + if node_cc is not None: + want = node_cc[1] + exact = minor = ptx = None + for entry in built: + cc = _cc(entry) + if cc is None: + continue + kind, version, suffix = cc + if kind == "sm": + if version == want: + exact = exact or entry + elif suffix != "a" and version[0] == want[0] and version[1] <= want[1]: + minor = minor or entry + elif suffix == "a": + ptx = ptx or (entry if version == want else None) + elif suffix == "f": + ptx = ptx or (entry if version[0] == want[0] and version[1] <= want[1] else None) + elif version <= want: + ptx = ptx or entry + if exact: + return None, None + if strict: + return (f"--strict-arch: the image is built for {'/'.join(built)}, no cubin of exactly {arch}; " + f"node {node.name} has {have}"), None + if minor: + return None, f"node {node.name} ({arch}) runs the {minor} cubin: {MINOR_RULE_NOTE}" + if ptx: + return None, f"node {node.name} ({arch}) JIT-compiles the {ptx} PTX: {PTX_RULE_NOTE}" + return f"the image is built for {'/'.join(built)}; node {node.name} has {have} ({CUDA_RULE})", None + if _gfx(arch) in {_gfx(a) for a in built}: + return None, None + return (f"the image is built for {'/'.join(built)}; node {node.name} has {have} (ROCm: the node's gfx target " + "must be built)"), None + + +def card_arch_problem(facts: ImageFacts, node: Node, *, strict: bool = False) -> str | None: + """The problem of :func:`card_arch_fit` (None: the image serves the node's cards).""" + return card_arch_fit(facts, node, strict=strict)[0] + + +def fit_problems(request: AdoptRequest, ref: str, facts: ImageFacts, + engine: str) -> tuple[list[str], list[str], list[str]]: + """``(problems, warnings, notes)`` of the image on every node of the role (each names + the node; a note says a node passed by a compatibility rule, :func:`card_arch_fit`). + The trainer floor and a catalog sampler image's record are the existing rules + (:func:`.trainer_image_check.image_problem`, :func:`.engine_images.image_mismatch`).""" + problems: list[str] = [] + warnings: list[str] = [] + notes: list[str] = [] + need = ENGINE_PACKAGES.get((request.role, engine), ()) + if need and not any(p in facts.packages for p in need): + problems.append(f"the image has no {request.role} engine {engine} (none of {list(need)} is installed; " + f"found {sorted(facts.packages) or 'no package'})") + for node in request.nodes: + if facts.cpu_arch and facts.cpu_arch != node.cpu_arch: + problems.append(f"the image is {facts.cpu_arch}; node {node.name} is {node.cpu_arch}") + continue + family = engine_images.canonical_device_family(node.device_family) + if family == "cuda" and not facts.cuda: + problems.append(f"the image's torch has no CUDA build (torch {facts.torch or 'missing'}); node " + f"{node.name} is a CUDA node") + continue + if family == "rocm" and not facts.hip: + problems.append(f"the image's torch has no ROCm build (torch {facts.torch or 'missing'}); node " + f"{node.name} is a ROCm node") + continue + if family in ("cuda", "rocm"): + why, note = card_arch_fit(facts, node, strict=request.strict_arch) + if why: + problems.append(why) + continue + if note: + notes.append(note) + if request.role == "trainer": + found = trainer_image_check.image_problem(ref, node.card, attention_backend=request.attention_backend) + if found: + (problems if found[1] else warnings).append(f"node {node.name}: {found[0]}") + else: + why = engine_images.image_mismatch(ref, cpu_arch=node.cpu_arch, device_family=node.device_family, + card_arch=node_card_arch(node), model=request.model) + if why: + problems.append(f"node {node.name}: {why}") + return problems, warnings, notes + + +def default_engine(request: AdoptRequest, facts: ImageFacts | None) -> str: + """The engine of the record: the one asked for, else the default training backend + (trainer) or the engine package the probe found (sampler: vllm-ascend, vllm, sglang).""" + if request.engine: + return request.engine.lower() + if request.role == "trainer": + from ..rl.engine import backends # noqa: PLC0415 + + return backends.DEFAULT_BACKEND + packages = facts.packages if facts else {} + return next((e for e, pkg in (("vllm-ascend", "vllm-ascend"), ("vllm", "vllm"), ("sglang", "sglang")) + if pkg in packages), "vllm") + + +# --- the steps in order ---------------------------------------------------------------- + + +SmokeFn = Callable[["Adopter", str, ImageFacts, str], StepResult] + + +class Adopter: + """The five steps over ``ops`` (an ``SshOps``: ``run(node, script, timeout=)``; tests + pass a fake). ``smoke``: step 5 (``(adopter, pinned ref, facts, engine) -> + StepResult``); ``urlopen`` / ``login``: the registry access of step 1.""" + + def __init__(self, request: AdoptRequest, *, ops: Any = None, smoke: SmokeFn | None = None, + urlopen=None, login: Mapping[str, str] | None | bool = True, + clock: Callable[[], float] = time.time, log: Callable[[str], None] | None = None) -> None: + if ops is None: + from .ssh_trainer_island import SshOps # noqa: PLC0415 + + ops = SshOps() + self.request = request + self.ops = ops + self.smoke = smoke + self.urlopen = urlopen + self.login = login + self.clock = clock + self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self.report = AdoptReport(request) + self.holding: list[str] = [] # the nodes the image was pulled on so far + + def _held(self, error: AdoptError) -> AdoptError: + """``error`` naming the nodes that hold the image (:attr:`holding`): the image + stays there, a retry reuses it, `` rmi`` frees the room.""" + if not self.holding or error.holding: + return error + from .node_inventory import profile_of # noqa: PLC0415 + + ref = self.report.pinned or self.request.ref + nodes = ", ".join(self.holding) + engine = profile_of(self.request.probe_node).container + engine = ("sudo -n " if self.request.container_sudo else "") + (engine if engine in ("docker", "podman") + else "docker") + return AdoptError(error.step, f"{error.reason}; the image stays pulled on {nodes} (a retry reuses it; " + f"`{engine} rmi {ref}` there frees the room)", holding=self.holding) + + def _hold(self, *names: str) -> None: + self.holding += [n for n in names if n not in self.holding] + + def _step(self, name: str, fn: Callable[[], tuple[str, dict[str, Any]]]) -> dict[str, Any]: + self.log(f"[image adopt] {name} ...") + t0 = self.clock() + try: + detail, data = fn() + except AdoptError as error: + self.report.steps.append(StepResult(name, False, error.reason, self.clock() - t0)) + raise self._held(error) from None + self.report.steps.append(StepResult(name, True, detail, self.clock() - t0, data)) + return data + + def run(self) -> AdoptReport: + """Every step in order; :class:`AdoptError` at the first that fails (the catalog is + not touched). On success the catalog has the record (:attr:`AdoptReport.record`).""" + req = self.request + self.checks() + pinned, facts = str(self.report.pinned), self.report.facts + assert facts is not None + engine = default_engine(req, facts) + if self.smoke is None: + raise self._held(AdoptError("smoke", f"no {req.role} smoke is wired for this adoption")) + self.log("[image adopt] smoke ...") + result = self.smoke(self, pinned, facts, engine) + self.report.steps.append(result) + if not result.ok: + raise self._held(AdoptError("smoke", result.detail)) + self.report.record = self._record(pinned, facts, engine, result) + self.report.catalog = site_images.add(self.report.record, req.catalog) + return self.report + + def checks(self) -> AdoptReport: + """Steps 1 to 4 only (no smoke, nothing written).""" + pinned = self._step("manifest", self._manifest)["ref"] + facts = self._step("probe", lambda: self._probe(pinned))["facts"] + engine = default_engine(self.request, facts) + self._step("fit", lambda: self._fit(pinned, facts, engine)) + self._step("pull", lambda: self._pull(pinned)) + return self.report + + # -- steps + def _manifest(self) -> tuple[str, dict[str, Any]]: + login = registry_login(self.request.ref) if self.login is True else (self.login or None) + pinned = pin(self.request.ref, login=login, urlopen=self.urlopen) + self.report.pinned = pinned + return pinned, {"ref": pinned} + + def _probe(self, ref: str) -> tuple[str, dict[str, Any]]: + node = self.request.probe_node + self._probe_host(node, ref) + self.check_idle(node, "probe") + facts = self._run_probe(node, ref, cards=False) + family = engine_images.canonical_device_family(node.device_family) + if not facts.arch_list and family in ("cuda", "rocm"): + self.log(f"[image adopt] torch's build flags name no card architecture; probing {node.name} again " + "with its cards") + facts = self._run_probe(node, ref, cards=True) + self.report.facts = facts + what = ", ".join(f"{k} {v}" for k, v in (("python", facts.python), ("torch", facts.torch), + ("cuda", facts.cuda), ("hip", facts.hip)) if v) + archs = "/".join(facts.arch_list) or "no card architecture" + return f"on {node.name}: {facts.cpu_arch or '?'}, {what}, built for {archs}", {"facts": facts} + + def _probe_host(self, node: Node, ref: str) -> None: + """ssh, the host probe and room in the image root on the probe node, before the + probe pulls the image there (the cluster preflight's checks).""" + from .preflight.cluster import FAIL, ClusterPreflight, Requirements # noqa: PLC0415 + + req = Requirements(min_image_root_free_gib=float(self.request.min_image_free_gib)) + checks = ClusterPreflight([node], image=ref, ops=self.ops, req=req, log=self.log, clock=self.clock, + engine=container_engine(node), sudo=self.request.container_sudo).hosts() + failed = [c for c in checks if c.status == FAIL and c.name in ("ssh", "host_probe", "disk_images")] + if failed: + raise AdoptError("probe", "; ".join(f"node {c.scope}: {c.name}: {c.detail}" + (f" ({c.fix})" if c.fix + else "") + for c in failed)) + + def check_idle(self, node: Node, step: str) -> None: + """Refuse (step ``step``) a node whose cards run a process or that runs a yeto + container (:func:`busy_script`); with ``allow_busy`` it is a warning.""" + from .node_inventory import profile_of # noqa: PLC0415 + + family = profile_of(node).family + try: + done = self.ops.run(node, busy_script(node, sudo=self.request.container_sudo), timeout=120.0) + text = (getattr(done, "stdout", "") or "") + "\n" + (getattr(done, "stderr", "") or "") + except Exception as error: # noqa: BLE001 - a dead ssh is the step's failure + raise AdoptError(step, f"node {node.name}: cannot read what runs on its cards: " + f"{type(error).__name__}: {error}") from None + apps, containers, readable = parse_busy(text, family) + if not readable: + self.log(f"[image adopt] WARNING: node {node.name}: no card tool to read its processes ({family}); " + "its cards are taken as idle") + busy = [f"process {a}" for a in apps] + [f"container {c}" for c in containers] + if not busy: + return + why = f"node {node.name} is in use: {', '.join(busy[:8])}" + if not self.request.allow_busy: + raise AdoptError(step, f"{why}; stop it, pick another node with --node, or pass --allow-busy") + self.log(f"[image adopt] WARNING: {why}; --allow-busy: the {step} runs there anyway") + + def _run_probe(self, node: Node, ref: str, *, cards: bool) -> ImageFacts: + try: + done = self.ops.run(node, probe_script(ref, node, cards=cards, sudo=self.request.container_sudo), + timeout=PROBE_TIMEOUT_S) + except AdoptError: + raise + except Exception as error: # noqa: BLE001 - a dead ssh or a timeout is the step's failure + raise AdoptError("probe", f"node {node.name}: {type(error).__name__}: {error}") from None + text = (getattr(done, "stdout", "") or "") + "\n" + (getattr(done, "stderr", "") or "") + if done.returncode != 0: + failure = image_pull.pull_failure(f"docker pull\n{text}") + why = failure.line if failure else text.strip()[-400:] + raise AdoptError("probe", f"node {node.name}: {container_engine(node)} run of {ref} failed " + f"(rc {done.returncode}): {why}") + self._hold(node.name) + facts = parse_probe(text) + if not facts.python: + raise AdoptError("probe", f"node {node.name}: the image has no Python interpreter yeto can run " + f"(tried {list(PYTHONS)})") + return facts + + def _fit(self, ref: str, facts: ImageFacts, engine: str) -> tuple[str, dict[str, Any]]: + problems, warnings, notes = fit_problems(self.request, ref, facts, engine) + node = self.request.probe_node + if not node_card_arch(node): + problems.append(f"node {node.name} has {node.card} cards of no known architecture: the catalog " + "matches records by card architecture") + for warning in warnings: + self.log(f"[image adopt] WARNING: {warning}") + for note in notes: + self.log(f"[image adopt] note: {note}") + if problems: + raise AdoptError("fit", "; ".join(problems)) + detail = f"{engine} {self.request.role} image fits {len(self.request.nodes)} node(s)" + return detail + "".join(f"; {n}" for n in notes), {"warnings": warnings, "notes": notes} + + def _pull(self, ref: str) -> tuple[str, dict[str, Any]]: + """Every node of the role pulls the image with its own container engine (its + profile's ``container``: docker or podman), the image root of that engine checked + first (docker's data root / containerd store, podman's graphroot).""" + from .preflight.cluster import FAIL, PASS, ClusterPreflight, Requirements # noqa: PLC0415 + + groups: dict[str, list[Node]] = {} + for n in self.request.nodes: + engine = engine_of(n) + if engine: + groups.setdefault(engine, []).append(n) + skipped = [n.name for n in self.request.nodes if not engine_of(n)] + if not groups: + raise AdoptError("pull", f"no {self.request.role} node runs a container engine (docker or podman): " + f"{skipped}") + req = Requirements(min_image_root_free_gib=float(self.request.min_image_free_gib)) + checks, pulled = [], True + for engine, nodes in sorted(groups.items()): + pf = ClusterPreflight(nodes, image=ref, ops=self.ops, req=req, log=self.log, clock=self.clock, + engine=engine, sudo=self.request.container_sudo) + found, ok = pf.pull() + checks += found + pulled = pulled and ok + self._hold(*(c.scope for c in checks if c.name == "image_pull" and c.status == PASS)) + failed = [c for c in checks if c.status == FAIL and c.name in ("ssh", "host_probe", "disk_images", + "image_pull")] + if failed or not pulled: + raise AdoptError("pull", "; ".join(f"node {c.scope}: {c.name}: {c.detail}" + (f" ({c.fix})" if c.fix + else "") + for c in failed) or "the pull did not run") + took = {c.scope: c.detail for c in checks if c.name == "image_pull"} + return (f"pulled on {len(took)} node(s)" + (f"; not pulled (no container engine): {skipped}" if skipped + else ""), + {"pulled": sorted(took)}) + + def _record(self, ref: str, facts: ImageFacts, engine: str, smoke: StepResult) -> site_images.SiteImage: + node = self.request.probe_node + steps = {s.name: round(s.seconds, 1) for s in self.report.steps} + evidence = {"at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "node": node.name, "seconds": round(sum(steps.values()), 1), "result": "pass", + "steps": steps, "pulled": next((list(s.data.get("pulled", [])) for s in self.report.steps + if s.name == "pull"), []), + **({"smoke": smoke.data} if smoke.data else {})} + notes = [n for s in self.report.steps for n in (s.data.get("notes") or [])] + if notes: + evidence["notes"] = notes + arch = node_card_arch(node) + return site_images.parse_record({ + "model": self.request.model, "role": self.request.role, "engine": engine, "ref": ref, + "device_family": engine_images.canonical_device_family(node.device_family), + "cpu_arch": node.cpu_arch, "card_archs": [arch] if arch else [], "versions": facts.versions(), + "evidence": evidence, "status": site_images.VERIFIED}) diff --git a/yeto/launch/image_manifest.py b/yeto/launch/image_manifest.py index b44f443c6..328209037 100644 --- a/yeto/launch/image_manifest.py +++ b/yeto/launch/image_manifest.py @@ -95,16 +95,67 @@ def _basic(login: dict[str, str] | None) -> str | None: return base64.b64encode(raw).decode() +def _without_tag(name: str) -> str: + """``host/repo:tag`` -> ``host/repo`` (a ``host:port`` stays).""" + head, slash, last = name.rpartition("/") + return f"{head}{slash}{last.split(':', 1)[0]}" + + +def split_tagged_ref(ref: str) -> tuple[str, str, str]: + """``[docker:]/[:tag][@sha256:]`` -> (host, repo, tag or digest): the + digest when there is one, else the tag (``latest`` when none is given).""" + name = ref.removeprefix("docker:") + if "@" in name: # a digest wins over a tag written next to it (``name:tag@sha256:...``) + path, _, digest = name.partition("@") + return split_ref(f"{_without_tag(path)}@{digest}") + last = name.rsplit("/", 1)[-1] + tag = last.split(":", 1)[1] if ":" in last else "latest" + path = _without_tag(name) + if not path or not re.fullmatch(r"[\w][\w.-]{0,127}", tag): + raise ValueError(f"{ref!r} is not an image reference") + host, repo, _ = split_ref(f"{path}@sha256:{'0' * 64}") + return host, repo, tag + + def manifest_status(ref: str, login: dict[str, str] | None = None, *, timeout: float = 10.0, urlopen=None) -> tuple[str, str]: """``(status, detail)``: ``present`` (HTTP 200), ``missing`` (404), ``denied`` (401/403: absent, or private and no / a wrong login: a registry does not tell which; and a 400 to a request that carried the login: ECR answers a malformed or wrong login so) or ``unknown`` (the registry was not reached, or answered something else).""" - host, repo, digest = split_ref(ref) - url = f"https://{host}/v2/{repo}/manifests/{digest}" + status, detail, _ = _manifest_head(*split_ref(ref), login, timeout=timeout, urlopen=urlopen) + return status, detail + + +def pin_digest(ref: str, login: dict[str, str] | None = None, *, timeout: float = 10.0, + urlopen=None) -> tuple[str, str]: + """``(status, detail)`` of ``ref``'s manifest, by tag or by digest; ``present`` gives the + digest-pinned reference as the detail (``/@sha256:``, Docker Hub's + host kept as written). A tag's digest is the registry's ``Docker-Content-Digest``; a + registry that names none is ``unknown``.""" + host, repo, reference = split_tagged_ref(ref) + status, detail, headers = _manifest_head(host, repo, reference, login, timeout=timeout, urlopen=urlopen) + if status != PRESENT: + return status, detail + path = _without_tag(ref.removeprefix("docker:").split("@", 1)[0]) + if reference.startswith("sha256:"): + return PRESENT, f"{path}@{reference}" + digest = next((v for k, v in headers.items() if k.lower() == "docker-content-digest"), "") + if not re.fullmatch(r"sha256:[0-9a-f]{64}", str(digest)): + return UNKNOWN, f"{host}/{repo}:{reference}: the registry named no sha256 digest for the tag" + return PRESENT, f"{path}@{digest}" + + +def _manifest_head(host: str, repo: str, reference: str, login: dict[str, str] | None, *, timeout: float, + urlopen) -> tuple[str, str, dict]: + """:func:`manifest_status` of ``reference`` (a digest or a tag), and the headers of the + answer that decided it.""" + url = f"https://{host}/v2/{repo}/manifests/{reference}" basic = _basic(login) urlopen = urlopen or _OPENER.open + digest = reference + at = "@" if reference.startswith("sha256:") else ":" # a digest or a tag + final: dict = {} def head(auth: str | None) -> tuple[int, dict]: headers = {"Accept": ACCEPT, **({"Authorization": auth} if auth else {})} @@ -117,12 +168,13 @@ def head(auth: str | None) -> tuple[int, dict]: sent_login = False # the code below answers a request (or token request) that carried the login try: code, headers = head(None) + final = headers if code == 401: challenge = next((v for k, v in headers.items() if k.lower() == "www-authenticate"), "") if challenge.lower().startswith("bearer"): params = dict(re.findall(r'(\w+)="([^"]*)"', challenge)) if "realm" not in params: - return UNKNOWN, f"{host}: a Bearer challenge without a realm" + return UNKNOWN, f"{host}: a Bearer challenge without a realm", final query = urllib.parse.urlencode({k: params[k] for k in ("service", "scope") if k in params}) try: with _open(f"{params['realm']}?{query}", method="GET", timeout=timeout, urlopen=urlopen, @@ -133,21 +185,24 @@ def head(auth: str | None) -> tuple[int, dict]: code, sent_login = int(error.code), bool(basic and params["realm"].startswith("https://")) else: token = body.get("token") or body.get("access_token") - code = head(f"Bearer {token}")[0] if token else 401 + if token: + code, final = head(f"Bearer {token}") + else: + code = 401 elif basic: - code, sent_login = head(f"Basic {basic}")[0], True + (code, final), sent_login = head(f"Basic {basic}"), True except (urllib.error.URLError, OSError, ValueError) as error: - return UNKNOWN, f"{host} not reached ({type(error).__name__}: {error})"[:300] + return UNKNOWN, f"{host} not reached ({type(error).__name__}: {error})"[:300], {} if code == 200: - return PRESENT, f"{host}/{repo}@{digest}" + return PRESENT, f"{host}/{repo}{at}{digest}", final if code == 404: - return MISSING, f"{host}/{repo} has no manifest {digest}" + return MISSING, f"{host}/{repo} has no manifest {digest}", final if code == 400 and sent_login: - return DENIED, (f"{host} rejected the registry login given for {repo}@{digest} (HTTP 400): a malformed " + return DENIED, (f"{host} rejected the registry login given for {repo}{at}{digest} (HTTP 400): a malformed " "or wrong password (an ECR password is `aws ecr get-login-password`, valid 12 hours); a registry " - f"that answers 400 for another reason: {CHECK_ENV}=off skips this check") + f"that answers 400 for another reason: {CHECK_ENV}=off skips this check"), final if code in (401, 403): how = "with the registry login given" if login else "anonymously" - return DENIED, (f"{host}/{repo}@{digest} is not readable {how} (HTTP {code}): it is not in that " - "registry, or it is private and needs a registry login") - return UNKNOWN, f"{host} answered HTTP {code} for {repo}@{digest}" + return DENIED, (f"{host}/{repo}{at}{digest} is not readable {how} (HTTP {code}): it is not in that " + "registry, or it is private and needs a registry login"), final + return UNKNOWN, f"{host} answered HTTP {code} for {repo}{at}{digest}", final diff --git a/yeto/launch/preflight/cluster.py b/yeto/launch/preflight/cluster.py index e7c09b64b..758d8d550 100644 --- a/yeto/launch/preflight/cluster.py +++ b/yeto/launch/preflight/cluster.py @@ -474,13 +474,40 @@ def disjoint_pairs(n: int) -> list[list[tuple[int, int]]]: ) -def host_sections(node: Node) -> list[tuple[str, str]]: - paths = ["/", "/var/lib/containerd", "$(docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)", - *[shlex.quote(p) for p in sorted(node.mounts)]] +def engine_command(engine: str = "docker", sudo: bool = False) -> str: + """The container engine as a node runs it: ``sudo -n `` with ``sudo`` (the + rootful store of an ssh sampler pool's ``container.sudo``), else ````.""" + return ("sudo -n " if sudo else "") + engine + + +def podman_root(sudo: bool = False) -> str: + """podman's storage graphroot (nothing printed when podman does not say: the image + store's disk is then not confirmed, :func:`host_checks`).""" + return f"{engine_command('podman', sudo)} info --format '{{{{.Store.GraphRoot}}}}' 2>/dev/null" + + + +def host_sections(node: Node, *, engine: str = "docker", sudo: bool = False) -> list[tuple[str, str]]: + """The host probe's sections. ``engine`` ``podman``: the image root read is podman's + storage graphroot (section ``podman_root``) instead of docker's data root; ``sudo``: + the engine runs as ``sudo -n `` (its rootful store). docker without sudo: + the sections of the preflight, unchanged.""" + if engine == "podman": + root = f"$({podman_root(sudo)})" + elif sudo: + root = f"$({engine_command(engine, sudo)} info -f '{{{{.DockerRootDir}}}}' 2>/dev/null || echo /var/lib/docker)" + else: + root = "$(docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)" + paths = ["/", "/var/lib/containerd", root, *[shlex.quote(p) for p in sorted(node.mounts)]] + extra = [("podman_root", podman_root(sudo))] if engine == "podman" else [] + base = list(HOST_SECTIONS_BASE) + if sudo and engine == "docker": # the docker info the image root and docker checks read: through sudo too + base = [(name, f"{engine_command(engine, sudo)} info --format '{{{{json .}}}}'" if name == "docker" else cmd) + for name, cmd in base] disk = ("for p in " + " ".join(f'"{p}"' if p.startswith("$(") else p for p in paths) + "; do " "if [ -e \"$p\" ]; then printf '%s\\t%s\\t%s\\n' \"$p\" \"$(findmnt -n -o FSTYPE -T \"$p\" 2>/dev/null)\" " "\"$(df -P -k \"$p\" | tail -1)\"; else printf '%s\\t-\\tmissing\\n' \"$p\"; fi; done") - return [*HOST_SECTIONS_BASE, ("disk", disk)] + return [*base, *extra, ("disk", disk)] CONTAINER_SECTIONS = ( @@ -509,6 +536,8 @@ class NodeState: tools: dict[str, str] = field(default_factory=dict) ports_from_container: bool = False pulled: bool = True + engine: str = "docker" # the container engine whose image root and pull are checked + sudo: bool = False # the engine runs as sudo -n (a pool's container.sudo: its rootful store) @property def name(self) -> str: @@ -700,11 +729,22 @@ def add(check: str, status: str, detail: str, fix: str = "", **data: Any) -> Non want = "/var/lib/containerd" if snap else str(info.get("DockerRootDir") or "/var/lib/docker") label = f"{want} ({'containerd image store' if snap else 'docker data root'})" image_roots = {label: d for d in disks if d.path == want} # noqa: B035 - one path + fix = "move it to NVMe (docker data-root; bind-mount /var/lib/containerd: it does not follow data-root)" + if state.engine == "podman": + root = h["podman_root"].text.strip() if _ok(h.get("podman_root")) else "" + image_roots = {f"{root} (podman graphroot)": d for d in disks if root and d.path == root} + fix = "move it to NVMe (graphroot in /etc/containers/storage.conf)" + if not image_roots: + who = engine_command("podman", state.sudo) + why = (f"`{who} info` printed no storage graphroot" if not root + else f"the graphroot {root} that `{who} info` printed is not on the node") + add("disk_images", FAIL, f"cannot confirm the disk of the image store: {why}", + f"check that `{who} info` runs on the node" + (" (sudo -n: passwordless sudo)" if state.sudo + else "")) for label, d in image_roots.items(): if d.free_gib < req.min_image_root_free_gib: - add("disk_images", FAIL, f"{label} on {d.mountpoint}: {d.free_gib:.0f} GiB free", - "move it to NVMe (docker data-root; bind-mount /var/lib/containerd: it does not " - "follow data-root)", free_gib=d.free_gib) + add("disk_images", FAIL, f"{label} on {d.mountpoint}: {d.free_gib:.0f} GiB free", fix, + free_gib=d.free_gib) else: add("disk_images", PASS, f"{label} on {d.mountpoint}: {d.free_gib:.0f} GiB free") # docker @@ -1072,8 +1112,14 @@ def __init__(self, nodes: Sequence[Node], *, image: str | None = None, ops: SshO req: Requirements | None = None, steps: Steps | None = None, out_dir: Path | None = None, log: Callable[[str], None] = lambda m: print(m, file=sys.stderr, flush=True), clock: Callable[[], float] = time.time, max_parallel: int = 32, - inventory: Sequence[Node] | None = None) -> None: + inventory: Sequence[Node] | None = None, engine: str = "docker", sudo: bool = False) -> None: + """``engine``: the container engine whose image root the host probe checks and + that :meth:`pull` pulls with (``docker``, the trainer's; ``podman`` for + ``yeto image adopt`` on podman nodes); ``sudo``: it runs as ``sudo -n `` + (an ssh sampler pool's ``container.sudo``: the rootful store).""" self.nodes = list(nodes) + self.engine = engine + self.sudo = bool(sudo) self.inventory = list(inventory) if inventory is not None else None # decides "grouped" # nodes, or node pairs, at once. At least 2: the two ends of a pair (ib_write_bw # server and client, the two NCCL ranks) must run together, or the server waits @@ -1089,7 +1135,7 @@ def __init__(self, nodes: Sequence[Node], *, image: str | None = None, ops: SshO self.log = log self.clock = clock self.multi = len(self.nodes) > 1 - self.states = [NodeState(n) for n in self.nodes] + self.states = [NodeState(n, engine=engine, sudo=self.sudo) for n in self.nodes] # -- helpers def _raw(self, step: str, name: str, text: str) -> None: @@ -1148,6 +1194,23 @@ def run(self) -> Report: (self.out_dir / "preflight.txt").write_text(report.table()) return report + def pull(self, *, blocking: Sequence[str] = ("ssh", "host_probe", "disk_images")) -> tuple[list[Check], bool]: + """``(checks, pulled)``: ssh and the host probes on every node, then, when no node + failed a ``blocking`` check (an unreachable node, an image root without room for + the image), the image pull on every docker node (``yeto image adopt``'s pre-pull). + ``pulled`` is False when the pull was not run or a node's pull failed.""" + checks = self.hosts() + if any(c.status == FAIL and c.name in blocking for c in checks): + return checks, False + checks += self._pull([s for s in self.states if s.reachable]) + return checks, all(c.status != FAIL for c in checks if c.name == "image_pull") + + def hosts(self) -> list[Check]: + """ssh and the host probes on every node (the disk, docker and card checks of the + host): what ``yeto image adopt`` asks of its probe node before the image runs there.""" + checks = self._reach() + return checks + self._host([s for s in self.states if s.reachable]) + def _reach(self) -> list[Check]: self.log(f"[preflight] ssh + clock on {len(self.states)} node(s)") @@ -1182,7 +1245,8 @@ def _host(self, live: Sequence[NodeState]) -> list[Check]: self.log(f"[preflight] host probes on {len(live)} node(s)") def one(state: NodeState) -> list[Check]: - _, text = self._run(state.node, probe_script(host_sections(state.node)), 300.0, "host") + _, text = self._run(state.node, probe_script(host_sections(state.node, engine=state.engine, + sudo=state.sudo)), 300.0, "host") state.host = parse_sections(text) if not state.host: return [Check(state.name, "host_probe", FAIL, f"the host probe printed nothing: {_tail(text, 200)}", @@ -1195,13 +1259,15 @@ def one(state: NodeState) -> list[Check]: return [c for cs in self._parallel(one, live) for c in cs] def _pull(self, live: Sequence[NodeState]) -> list[Check]: - docker = [s for s in live if s.node.runtime == "docker"] - self.log(f"[preflight] docker pull on {len(docker)} node(s)") + engine, command = self.engine, engine_command(self.engine, self.sudo) + # docker: the nodes that run docker (the trainer's); another engine: every node it was asked for + docker = [s for s in live if s.node.runtime == "docker"] if engine == "docker" else list(live) + self.log(f"[preflight] {command} pull on {len(docker)} node(s)") def one(state: NodeState) -> Check: image = str(self.image or state.node.image) t0 = self.clock() - rc, text = self._run(state.node, f"docker pull -q {shlex.quote(image)}", 3600.0, "pull") + rc, text = self._run(state.node, f"{command} pull -q {shlex.quote(image)}", 3600.0, "pull") if rc == 0: return Check(state.name, "image_pull", PASS, f"{image[:90]} ({self.clock() - t0:.0f} s)") state.pulled = False @@ -1211,7 +1277,7 @@ def one(state: NodeState) -> Check: "docker/miles-ports/make_layer.py") elif "no space left" in text.lower(): fix = "free the docker data root / /var/lib/containerd (put them on NVMe)" - return Check(state.name, "image_pull", FAIL, f"docker pull failed (rc {rc}): {_tail(text, 240)}", fix) + return Check(state.name, "image_pull", FAIL, f"{command} pull failed (rc {rc}): {_tail(text, 240)}", fix) return self._parallel(one, docker) diff --git a/yeto/launch/rl_backend.py b/yeto/launch/rl_backend.py index 0f5cc7207..bad7b80bd 100644 --- a/yeto/launch/rl_backend.py +++ b/yeto/launch/rl_backend.py @@ -79,7 +79,10 @@ def _site_catalog_trainer_nodes(args) -> tuple[list | None, str]: if not n.roles or any(r == "trainer" or r.startswith("trainer-") for r in n.roles)] except (ValueError, InventoryError): # the launch's own checks name a bad --gpu or inventory return None, "" - if not nodes or any(n.image for n in nodes): + # the island's own nodes decide whether the configuration names its image; a spare that + # names one for itself (trainer-spare with image:) does not turn the catalog off + own = [n for n in nodes if not n.roles or "trainer" in n.roles] + if not nodes or any(n.image for n in own): return None, "" if not all(cloud == "ssh" for cloud in clouds): return None, MIXED_FLEET