Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
690 changes: 690 additions & 0 deletions tests/test_image_adopt.py

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions tests/test_run_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions tests/test_site_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
784 changes: 784 additions & 0 deletions yeto/launch/image_adopt.py

Large diffs are not rendered by default.

81 changes: 68 additions & 13 deletions yeto/launch/image_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:]<host>/<repo>[:tag][@sha256:<hex>]`` -> (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 (``<host>/<repo>@sha256:<hex>``, 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 {})}
Expand All @@ -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,
Expand All @@ -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
94 changes: 80 additions & 14 deletions yeto/launch/preflight/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <engine>`` with ``sudo`` (the
rootful store of an ssh sampler pool's ``container.sudo``), else ``<engine>``."""
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 <engine>`` (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 = (
Expand Down Expand Up @@ -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 <engine> (a pool's container.sudo: its rootful store)

@property
def name(self) -> str:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 <engine>``
(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
Expand All @@ -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:
Expand Down Expand Up @@ -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)")

Expand Down Expand Up @@ -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)}",
Expand All @@ -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
Expand All @@ -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)

Expand Down
5 changes: 4 additions & 1 deletion yeto/launch/rl_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading