Skip to content

API reference

Every name is imported from ms_env.

ms_env

Environments for MolSuite apps: a recipe says how to tell that a tool works and how to install it, a host says where, and ensure applies one to the other.

The lowest layer of MolSuite: the standard library, no Qt, and nothing of ms_flow.

Modules:

Name Description
app

The environment of an app on a host: the Python that runs here, with the same versions of

connect

Log in to a machine once with its password, so that from then on ssh gets in alone.

exits

What a tool's exit code means: its recipe's [exit_codes], then what any program's means

host

A host: where commands run. This machine, or another reached with the system's ssh.

locking

A short filesystem lock on an environment prefix, for the installs and removals of every client.

recipes

External tools: find one that already works, or install it -- driven by a TOML file.

steps

Steps: named units of work that run one after another, their output read line by line.

Classes:

Name Description
ToolFailed

tool exited with code: what that means, and the last of what it said (output).

Install
Recipe
RecipeStep
ToolSpec
Step

One named unit of work: a command line, or an in-process call. run is a call that

StepFailed
Host

A machine, known by what running a command on it gives back: address as ssh knows it (its

HostError
Locked

The prefix is another client's now: owner is what it wrote (client, pid, since);

Functions:

Name Description
app_recipe

The recipe that gives a host the environment requirements run in here.

meaning

What exit code means: codes (a recipe's [exit_codes], keyed by the code as text or

ensure

Make sure the tool is there: start installing it, or join the install already running.

locate

(READY, executable) or (MISSING | UNREACHABLE, ""). Blocks on a subprocess: keep it off UI threads.

recipe_steps

The whole install: clear what ms_env left at the prefix, run the recipe, stamp it.

remove

Delete the prefix when ms_env installed it. False: nothing of ours there, nothing deleted.

status

READY, MISSING or UNREACHABLE. Blocks like locate, which also says where the tool is.

verify

What the environment at the recipe's prefix lacks of what the recipe asks for; [] when it meets it.

find_environment_manager

The program that creates environments here: micromamba, unless a variable names another.

run_step

Run one step, streaming its output. Raises StepFailed on failure.

run_steps
conda_platform

linux-64, osx-arm64, win-64...; system-machine for one conda has no name for.

prefix_lock

Fail closed (Locked) when another client owns this prefix; no background service.

unlock

Remove the lock of prefix, whoever took it, and return what its owner wrote ({} for no lock).

Attributes:

Name Type Description
MISSING
READY
STAMP
UNREACHABLE
LOCAL

MISSING module-attribute

MISSING = 'missing'

READY module-attribute

READY = 'ready'

STAMP module-attribute

STAMP = '.ms_env.json'

UNREACHABLE module-attribute

UNREACHABLE = 'unreachable'

LOCAL module-attribute

LOCAL = Host()

ToolFailed

ToolFailed(tool: str, code: int, output: str = '', codes: dict | None = None)

Bases: RuntimeError

tool exited with code: what that means, and the last of what it said (output).

Methods:

Name Description
__reduce__
Source code in src/ms_env/exits.py
40
41
42
43
44
def __init__(self, tool: str, code: int, output: str = "", codes: dict | None = None):
    self.tool, self.code, self.output, self.meaning = tool, code, output, meaning(code, codes)
    said = f" ({self.meaning})" if self.meaning else ""
    tail = output.strip()[-1000:]
    super().__init__(f"{tool} exited with {code}{said}" + (f": {tail}" if tail else ""))

__reduce__

__reduce__()
Source code in src/ms_env/exits.py
46
47
def __reduce__(self):  # across processes: the words, already made
    return _again, (self.tool, self.code, self.output, self.meaning, str(self))

Install dataclass

Install(key: str, future: Future = Future(), lines: list[str] = list(), done: int = 0, total: int = 1, step: str = '')

Attributes:

Name Type Description
key str
future Future
lines list[str]
done int
total int
step str

key instance-attribute

key: str

future class-attribute instance-attribute

future: Future = field(default_factory=Future)

lines class-attribute instance-attribute

lines: list[str] = field(default_factory=list)

done class-attribute instance-attribute

done: int = 0

total class-attribute instance-attribute

total: int = 1

step class-attribute instance-attribute

step: str = ''

Recipe dataclass

Recipe(name: str, prefix: str, candidates: tuple[str, ...], commands: tuple[str, ...], check: tuple[str, ...], steps: tuple[RecipeStep, ...], conda: tuple[str, ...] = (), pip: tuple[str, ...] = (), stamp: str = '', refresh: tuple[RecipeStep, ...] = (), base: str = '', platform: str = '', unsupported: str = '')

Attributes:

Name Type Description
name str
prefix str
candidates tuple[str, ...]
commands tuple[str, ...]
check tuple[str, ...]
steps tuple[RecipeStep, ...]
conda tuple[str, ...]
pip tuple[str, ...]
stamp str
refresh tuple[RecipeStep, ...]
base str
platform str
unsupported str

name instance-attribute

name: str

prefix instance-attribute

prefix: str

candidates instance-attribute

candidates: tuple[str, ...]

commands instance-attribute

commands: tuple[str, ...]

check instance-attribute

check: tuple[str, ...]

steps instance-attribute

steps: tuple[RecipeStep, ...]

conda class-attribute instance-attribute

conda: tuple[str, ...] = ()

pip class-attribute instance-attribute

pip: tuple[str, ...] = ()

stamp class-attribute instance-attribute

stamp: str = ''

refresh class-attribute instance-attribute

refresh: tuple[RecipeStep, ...] = ()

base class-attribute instance-attribute

base: str = ''

platform class-attribute instance-attribute

platform: str = ''

unsupported class-attribute instance-attribute

unsupported: str = ''

RecipeStep dataclass

RecipeStep(name: str, argv: tuple[str, ...] = (), timeout: float = 1800.0, send: tuple[str, ...] = (), url: str = '', sha256: str = '', to: str = '', downloads: tuple[tuple[str, str, str], ...] = (), local: Callable[[Callable[[str], None]], None] | None = None)

Attributes:

Name Type Description
name str
argv tuple[str, ...]
timeout float
send tuple[str, ...]
url str
sha256 str
to str
downloads tuple[tuple[str, str, str], ...]
local Callable[[Callable[[str], None]], None] | None

name instance-attribute

name: str

argv class-attribute instance-attribute

argv: tuple[str, ...] = ()

timeout class-attribute instance-attribute

timeout: float = 1800.0

send class-attribute instance-attribute

send: tuple[str, ...] = field(default=(), repr=False)

url class-attribute instance-attribute

url: str = field(default='', repr=False)

sha256 class-attribute instance-attribute

sha256: str = field(default='', repr=False)

to class-attribute instance-attribute

to: str = field(default='', repr=False)

downloads class-attribute instance-attribute

downloads: tuple[tuple[str, str, str], ...] = field(default=(), repr=False)

local class-attribute instance-attribute

local: Callable[[Callable[[str], None]], None] | None = field(default=None, repr=False, compare=False)

ToolSpec dataclass

ToolSpec(name: str, version: str, info: dict[str, Any], prefix: str, paths: tuple[str, ...], commands: tuple[str, ...], check: tuple[str, ...], conda: tuple[str, ...] = (), pip: tuple[str, ...] = (), channels: tuple[str, ...] = ('conda-forge',), steps: tuple[RecipeStep, ...] = (), exit_codes: dict[int, str] = dict())

Methods:

Name Description
failed

The error to raise when the tool exited with code: says what that code means.

load
recipe

Bind the templates to one host. tools_home/prefix are paths on that host.

Attributes:

Name Type Description
name str
version str
info dict[str, Any]
prefix str
paths tuple[str, ...]
commands tuple[str, ...]
check tuple[str, ...]
conda tuple[str, ...]
pip tuple[str, ...]
channels tuple[str, ...]
steps tuple[RecipeStep, ...]
exit_codes dict[int, str]

name instance-attribute

name: str

version instance-attribute

version: str

info instance-attribute

info: dict[str, Any]

prefix instance-attribute

prefix: str

paths instance-attribute

paths: tuple[str, ...]

commands instance-attribute

commands: tuple[str, ...]

check instance-attribute

check: tuple[str, ...]

conda class-attribute instance-attribute

conda: tuple[str, ...] = ()

pip class-attribute instance-attribute

pip: tuple[str, ...] = ()

channels class-attribute instance-attribute

channels: tuple[str, ...] = ('conda-forge',)

steps class-attribute instance-attribute

steps: tuple[RecipeStep, ...] = ()

exit_codes class-attribute instance-attribute

exit_codes: dict[int, str] = field(default_factory=dict)

failed

failed(code: int, output: str = '') -> ToolFailed

The error to raise when the tool exited with code: says what that code means.

Source code in src/ms_env/recipes.py
150
151
152
def failed(self, code: int, output: str = "") -> ToolFailed:
    """The error to raise when the tool exited with `code`: says what that code means."""
    return ToolFailed(self.name, code, output, self.exit_codes)

load classmethod

load(path: Path | str) -> 'ToolSpec'
Source code in src/ms_env/recipes.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@classmethod
def load(cls, path: Path | str) -> "ToolSpec":
    data = tomllib.loads(Path(path).read_text(encoding="utf-8"))
    tool, locate, env = data["tool"], data["locate"], data.get("env", {})
    return cls(
        name=str(tool["name"]),
        version=str(tool.get("version", "")),
        info=dict(tool),
        prefix=str(tool.get("prefix", "{tools_home}/{name}/{version}")),
        paths=tuple(locate.get("paths", ())),
        commands=tuple(locate.get("commands", ())),
        check=tuple(locate.get("check", ())),
        conda=tuple(env.get("conda", ())),
        pip=tuple(env.get("pip", ())),
        channels=tuple(env.get("channels", ("conda-forge",))),
        steps=tuple(map(_install_step, data.get("install", ()))),
        exit_codes={int(code): str(said) for code, said in data.get("exit_codes", {}).items()},
    )

recipe

recipe(tools_home: str, *, prefix: str = '', extra_paths: Iterable[str] = (), manager: str = '', platform: str = '') -> Recipe

Bind the templates to one host. tools_home/prefix are paths on that host.

prefix is a location the user chose instead of the managed one: an environment of their own (checked, never changed) or a place to install into. extra_paths are user-registered executables; manager is a conda-type program to use there instead of micromamba. platform is the host's (Host.platform()); this machine's by default.

Source code in src/ms_env/recipes.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def recipe(
    self,
    tools_home: str,
    *,
    prefix: str = "",
    extra_paths: Iterable[str] = (),
    manager: str = "",
    platform: str = "",
) -> Recipe:
    """Bind the templates to one host. ``tools_home``/``prefix`` are paths *on that host*.

    ``prefix`` is a location the user chose instead of the managed one: an environment of
    their own (checked, never changed) or a place to install into. ``extra_paths`` are
    user-registered executables; ``manager`` is a conda-type program to use there instead
    of micromamba. ``platform`` is the host's (``Host.platform()``); this machine's by default.
    """
    platform = platform or LOCAL.platform()
    values = {"tools_home": str(tools_home).rstrip("/\\"), "name": self.name, "version": self.version,
              "exe": "{exe}", "platform": platform}
    values["prefix"] = prefix = str(prefix or self.prefix.format_map(values)).rstrip("/\\")
    win = platform.startswith("win")
    values["bin"], values["python"] = (f"{prefix}/Library/bin", f"{prefix}/python.exe") if win else \
        (f"{prefix}/bin", f"{prefix}/bin/python")
    fill = lambda items: tuple(str(item).format_map(values) for item in items)  # noqa: E731
    steps = _env_steps(self.name, fill(self.conda), fill(self.pip), fill(self.channels), values, manager)
    unsupported = ""
    for step in self.steps:
        if not step.downloads:
            steps.append(RecipeStep(step.name, fill(step.argv), step.timeout))
            continue
        build = next(((url, sha) for where, url, sha in step.downloads if where in ("", platform)), None)
        if build is None:
            unsupported = f"{self.name} has no build for {platform}"
            continue
        steps.append(RecipeStep(step.name, (), step.timeout, url=build[0], sha256=build[1], to=fill([step.to])[0]))
    # Downloads are out of the repr of a step, so a recipe without any keeps the stamp it had.
    downloads = tuple((step.to, step.downloads) for step in self.steps if step.downloads)
    material = (self.name, self.version, self.conda, self.pip, self.channels, self.steps)
    return Recipe(
        name=self.name,
        prefix=values["prefix"],
        candidates=(*map(str, extra_paths), *fill(self.paths)),
        commands=self.commands,
        check=fill(self.check),
        steps=tuple(steps),
        conda=fill(self.conda),
        pip=fill(self.pip),
        stamp=hashlib.sha256(repr(material + ((downloads,) if downloads else ())).encode()).hexdigest()[:16],
        platform=platform,
        unsupported=unsupported,
    )

Step dataclass

Step(name: str, argv: Optional[list[str]] = None, call: Optional[Callable[[], str]] = None, timeout: float = DEFAULT_TIMEOUT, run: Optional[Callable[[Callable[[str], None]], None]] = None)

One named unit of work: a command line, or an in-process call. run is a call that prints as it goes: it gets the function each line goes to.

Attributes:

Name Type Description
name str
argv Optional[list[str]]
call Optional[Callable[[], str]]
timeout float
run Optional[Callable[[Callable[[str], None]], None]]

name instance-attribute

name: str

argv class-attribute instance-attribute

argv: Optional[list[str]] = None

call class-attribute instance-attribute

call: Optional[Callable[[], str]] = None

timeout class-attribute instance-attribute

timeout: float = DEFAULT_TIMEOUT

run class-attribute instance-attribute

run: Optional[Callable[[Callable[[str], None]], None]] = None

StepFailed

Bases: RuntimeError

Host

Host(address: str | None = None, ssh=('ssh', '-o', 'BatchMode=yes', *_SHARED))

A machine, known by what running a command on it gives back: address as ssh knows it (its keys, users and jumps are in ~/.ssh/config), or None for this one.

Methods:

Name Description
__repr__
argv

What to execute here for sh to run command there. This machine needs an sh for

run

What command printed there, given data (bytes, or an open file) to read.

home

The home of the account there: where a path of ours on that machine starts.

platform

The platform there, as conda names it (see conda_platform).

Source code in src/ms_env/host.py
42
43
44
45
def __init__(self, address: str | None = None, ssh=("ssh", "-o", "BatchMode=yes", *_SHARED)):
    self.address, self.ssh = address or None, tuple(ssh)
    if self.address and _SHARED and _SHARED[-1] in self.ssh:
        (Path.home() / ".ssh").mkdir(mode=0o700, exist_ok=True)

__repr__

__repr__() -> str
Source code in src/ms_env/host.py
47
48
def __repr__(self) -> str:
    return f"Host({self.address!r})"

argv

argv(command: str) -> list[str]

What to execute here for sh to run command there. This machine needs an sh for that, which Windows lacks: what ms_env does here it does in Python, not through this.

Source code in src/ms_env/host.py
50
51
52
53
def argv(self, command: str) -> list[str]:
    """What to execute here for `sh` to run `command` there. This machine needs an `sh` for
    that, which Windows lacks: what ms_env does here it does in Python, not through this."""
    return ["sh", "-c", command] if self.address is None else [*self.ssh, self.address, command]

run

run(command: str, data=b'', timeout: float = 600) -> bytes

What command printed there, given data (bytes, or an open file) to read.

Source code in src/ms_env/host.py
55
56
57
58
59
60
61
62
63
64
65
66
67
def run(self, command: str, data=b"", timeout: float = 600) -> bytes:
    """What `command` printed there, given `data` (bytes, or an open file) to read."""
    feed = {"input": data} if isinstance(data, bytes) else {"stdin": data}
    done = subprocess.run(self.argv(command), **feed, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          timeout=timeout)
    if done.returncode:
        said = done.stderr.decode(errors="replace").strip()
        if "Permission denied" in said:  # BatchMode: ssh does not ask, and here nobody could answer
            said += f"\nssh has to log in to {self.address} with a key, without asking: connect to it once (`ms_env.connect`) or see ssh-copy-id"
        if "Host key verification failed" in said:  # the same: nobody here to say yes to a new key
            said += f"\nssh does not know {self.address} yet: log in to it once by hand (`ssh {self.address}`)"
        raise HostError(f"`{command[:200]}` on {self.address or 'this machine'}: {said or done.returncode}")
    return done.stdout

home

home() -> str

The home of the account there: where a path of ours on that machine starts.

Source code in src/ms_env/host.py
69
70
71
72
73
def home(self) -> str:
    """The home of the account there: where a path of ours on that machine starts."""
    if self.address is None:
        return str(Path.home())
    return self.run('printf %s "$HOME"', timeout=60).decode()

platform

platform() -> str

The platform there, as conda names it (see conda_platform).

Source code in src/ms_env/host.py
75
76
77
78
79
def platform(self) -> str:
    """The platform there, as conda names it (see `conda_platform`)."""
    if self.address is None:
        return conda_platform(_platform.system(), _platform.machine())
    return conda_platform(*self.run("uname -sm", timeout=60).decode().split()[:2])

HostError

Bases: RuntimeError

Locked

Locked(prefix: str, host: Host, lock: str, owner: dict)

Bases: RuntimeError

The prefix is another client's now: owner is what it wrote (client, pid, since); unlock(prefix, host) removes the lock once that client is known to have stopped.

Source code in src/ms_env/locking.py
27
28
29
30
31
def __init__(self, prefix: str, host: Host, lock: str, owner: dict):
    self.prefix, self.host, self.lock, self.owner = prefix, host, lock, owner
    who = f"{owner.get('client', '?')} (pid {owner.get('pid', '?')}) since {owner.get('since', '?')}"
    super().__init__(f"environment is locked by {who}: {lock}; once that client stopped, "
                     "`ms_env.unlock` removes the lock")

app_recipe

app_recipe(name: str, requirements: Iterable[str], imports: Iterable[str], *, prefix: str, tools_home: str, cache: Path | str, manager: str = '', leave_out: Iterable[str] = ()) -> Recipe

The recipe that gives a host the environment requirements run in here.

requirements are the packages of the app, each name or name[extras]: one imported from a source checkout goes as a wheel of its code as it is now, one that is installed is asked for in the version it has. imports are the modules that have to import there for the environment to count as usable. prefix and tools_home are paths on the host (see Host.home); cache is a directory of this machine for the wheels. leave_out names what the host goes without, though the packages ask for it (a GUI where only their jobs run): what only those would bring is left out too.

The environment is updated where it stands for as long as the Python is the same. Builds wheels the first time, and after the code changes: keep it off UI threads.

Source code in src/ms_env/app.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def app_recipe(
    name: str,
    requirements: Iterable[str],
    imports: Iterable[str],
    *,
    prefix: str,
    tools_home: str,
    cache: Path | str,
    manager: str = "",
    leave_out: Iterable[str] = (),
) -> Recipe:
    """The recipe that gives a host the environment `requirements` run in here.

    `requirements` are the packages of the app, each `name` or `name[extras]`: one imported
    from a source checkout goes as a wheel of its code as it is now, one that is installed is
    asked for in the version it has. `imports` are the modules that have to import there for
    the environment to count as usable. `prefix` and `tools_home` are paths on the host (see
    `Host.home`); `cache` is a directory of this machine for the wheels.
    `leave_out` names what the host goes without, though the packages ask for it (a GUI where
    only their jobs run): what only those would bring is left out too.

    The environment is updated where it stands for as long as the Python is the same. Builds
    wheels the first time, and after the code changes: keep it off UI threads.
    """
    prefix, cache = str(prefix).rstrip("/"), Path(cache)
    code, wheels, wanted, tags, shipped, built = f"{prefix}/{_CODE}", [], [], [], {}, set()
    for requirement in requirements:
        dist, extras = re.fullmatch(r"\s*([\w.-]+)\s*(\[[^]]*])?\s*", requirement).groups()
        module = re.sub(r"[-.]+", "_", dist).lower()
        root = _checkout(module)
        if root is None:
            wanted.append(f"{dist}=={metadata.version(dist)}")
        else:
            tags.append(_tree_hash(root, module))
            wheels.append(_wheel(root, tags[-1], cache))
            wanted.append(f"{code}/{wheels[-1].name}")
            built.add(_canonical(dist))
        shipped[_canonical(dist)] = (_requires(wheels[-1] if root else dist), set(re.findall(r"[\w.-]+", extras or "")))
    needs = _needs(shipped, {_canonical(name) for name in leave_out})
    cache.mkdir(parents=True, exist_ok=True)
    constraints, loose = cache / "constraints.txt", cache / "constraints-pip.txt"
    everything, by_pip = _constraints(built)
    constraints.write_text(everything, encoding="utf-8")
    loose.write_text(by_pip, encoding="utf-8")

    pip = (f"{prefix}/bin/python", "-m", "pip", "install", "--progress-bar", "off")
    # ponytail: one version the index lacks drops every pin of what conda installed here, not
    # just that one. Drop them one by one if a host ever ends up too far from this environment.
    pinned = (
        'pip() { "$0" -m pip install --progress-bar off --constraint "$1" "${@:2}"; }; d=$1; shift; '
        'pip "$d/constraints.txt" "$@" || '
        '{ echo "not every version here can be had there: pinning what pip installed only"; '
        'pip "$d/constraints-pip.txt" "$@"; }'
    )
    refresh = [
        RecipeStep(
            f"send the code of {name}",
            ("sh", "-c", 'rm -rf "$0" && mkdir -p "$0" && tar -x -C "$0"', code),
            600.0,
            send=(str(constraints), str(loose), *map(str, wheels)),
        ),
        RecipeStep(
            f"install what {name} needs",
            ("bash", "-c", pinned, f"{prefix}/bin/python", code, *needs),
            3600.0,
        ),
        # Its own packages without what they ask for: `needs` is that, less `leave_out`. Forced, as
        # the version of a checkout does not change with its code and pip would keep the old one.
        RecipeStep(f"install {name}", (*pip, "--no-deps", "--force-reinstall", *wanted), 600.0),
    ]
    # `==`: conda reads `python=3.12.1` as 3.12.1*, which takes 3.12.10. Ray refuses a node whose
    # Python patch differs, and the check refuses a prefix whose python was changed by hand.
    python = platform.python_version()
    conda = (f"python=={python}", "pip")
    values = {"prefix": prefix, "tools_home": str(tools_home).rstrip("/")}
    short = lambda *parts: hashlib.sha256(repr(parts).encode()).hexdigest()[:16]  # noqa: E731
    return Recipe(
        name=name,
        prefix=prefix,
        candidates=(f"{prefix}/bin/python",),
        commands=(),
        check=("{exe}", "-c", f"import sys\nif sys.version.split()[0] != {python!r}: "
               f"sys.exit('python ' + sys.version.split()[0] + ', not {python}')\nimport " + ", ".join(imports)),
        steps=(*_env_steps(name, conda, (), ("conda-forge",), values, manager), *refresh),
        conda=conda,
        stamp=short(conda, wanted, needs, tags, constraints.read_text(encoding="utf-8")),
        refresh=tuple(refresh),
        base=short(conda),
    )

meaning

meaning(code: int, codes: dict | None = None) -> str

What exit code means: codes (a recipe's [exit_codes], keyed by the code as text or number) first; a signal (Python's negative code, or the shell's 128 + n); "" when unknown.

Source code in src/ms_env/exits.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def meaning(code: int, codes: dict | None = None) -> str:
    """What exit `code` means: `codes` (a recipe's `[exit_codes]`, keyed by the code as text or
    number) first; a signal (Python's negative code, or the shell's 128 + n); "" when unknown."""
    codes = {int(key): str(value) for key, value in (codes or {}).items()}
    if code in codes:
        return codes[code]
    number = -code if code < 0 else code - 128 if 128 < code < 160 else 0
    if number:
        with_name = _SIGNALS.get(number)
        if with_name:
            return with_name
        try:
            return f"ended by {signal.Signals(number).name}"
        except ValueError:
            pass
    return _SHELL.get(code, "")

ensure

ensure(recipe: Recipe, host: Host = LOCAL, busy: Callable[[], str] | None = None) -> Install

Make sure the tool is there: start installing it, or join the install already running.

Returns at once: wait on future and read lines for the log. Nothing is installed where the tool is already usable. An install of ours made from another recipe is made again, or brought up to this one where it stands when the recipe says how (that is the update); an environment of the user is verified and left as it is.

busy is asked only before an install of ours is changed: what it returns is why that cannot be done now (something is running from it), and the install fails saying so.

Source code in src/ms_env/recipes.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def ensure(recipe: Recipe, host: Host = LOCAL, busy: Callable[[], str] | None = None) -> Install:
    """Make sure the tool is there: start installing it, or join the install already running.

    Returns at once: wait on ``future`` and read ``lines`` for the log. Nothing is installed
    where the tool is already usable. An install of ours made from another recipe is made
    again, or brought up to this one where it stands when the recipe says how (that is the
    update); an environment of the user is verified and left as it is.

    ``busy`` is asked only before an install of ours is changed: what it returns is why that
    cannot be done now (something is running from it), and the install fails saying so.
    """
    key = f"{recipe.name}@{host.address or 'local'}"
    with _LOCK:
        current = _INSTALLS.get(key)
        if current is not None and not current.future.done():
            return current
        install = _INSTALLS[key] = Install(key)
    # ponytail: one daemon thread per install; a pool if installs pile up.
    # Daemon on purpose: quitting the app must not wait 30 min for a conda solve.
    threading.Thread(target=_run_install, args=(install, recipe, host, busy), name=f"ms_env-{key}", daemon=True).start()
    return install

locate

locate(recipe: Recipe, host: Host = LOCAL, timeout: float = 60.0) -> tuple[str, str]

(READY, executable) or (MISSING | UNREACHABLE, ""). Blocks on a subprocess: keep it off UI threads.

A candidate counts when it is there and its check passes; on Windows, path.exe for path.

Source code in src/ms_env/recipes.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
def locate(recipe: Recipe, host: Host = LOCAL, timeout: float = 60.0) -> tuple[str, str]:
    """(READY, executable) or (MISSING | UNREACHABLE, ""). Blocks on a subprocess: keep it off UI threads.

    A candidate counts when it is there and its check passes; on Windows, `path.exe` for `path`.
    """
    if host.address is None:
        return _locate_here(recipe, timeout)
    try:
        result = subprocess.run(
            host.argv(_locate_script(recipe)),
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False,
        )
    except subprocess.TimeoutExpired:
        return (UNREACHABLE if host.address else MISSING), ""
    found = result.stdout.strip().splitlines()
    if result.returncode == 0 and found:
        return READY, found[-1]
    return (UNREACHABLE if host.address and result.returncode == _SSH_CONNECT_FAILED else MISSING), ""

recipe_steps

recipe_steps(recipe: Recipe, host: Host = LOCAL, refresh: bool = False) -> list[Step]

The whole install: clear what ms_env left at the prefix, run the recipe, stamp it.

The first step fails on a prefix that holds something ms_env did not install. With refresh the prefix stays and only recipe.refresh runs before the stamp.

Source code in src/ms_env/recipes.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def recipe_steps(recipe: Recipe, host: Host = LOCAL, refresh: bool = False) -> list[Step]:
    """The whole install: clear what ms_env left at the prefix, run the recipe, stamp it.

    The first step fails on a prefix that holds something ms_env did not install. With
    `refresh` the prefix stays and only `recipe.refresh` runs before the stamp.
    """
    label, prefix = (f"{host.address}: " if host.address else ""), _prefix(recipe)
    if recipe.unsupported and not refresh:
        raise StepFailed(recipe.unsupported)
    clear = (
        f'p={prefix}\n'
        f'if [ -n "$(ls -A "$p" 2>/dev/null)" ] && [ ! -f "$p/{STAMP}" ] && [ ! -f "$p{_INSTALLING}" ]; then\n'
        '  echo "$p holds an environment ms_env did not install: it is checked, never changed." >&2; exit 1\n'
        "fi\n"
        f'mkdir -p "$(dirname "$p")" && : > "$p{_INSTALLING}" && rm -rf -- "$p"'
    )
    stamp = (
        f'p={prefix}\nmkdir -p "$p" && printf %s {shlex.quote(_stamp_text(recipe))} > "$p/{STAMP}" '
        f'&& rm -f "$p{_INSTALLING}"'
    )
    steps = (
        *(recipe.refresh if refresh else (
            RecipeStep(f"prepare {recipe.prefix}", ("sh", "-c", clear), 300.0, local=partial(_clear_here, recipe)),
            *recipe.steps,
        )),
        RecipeStep(f"record the {recipe.name} install", ("sh", "-c", stamp), 60.0, local=partial(_stamp_here, recipe)),
    )
    return [_step(step, label, host) for step in steps]

remove

remove(recipe: Recipe, host: Host = LOCAL) -> bool

Delete the prefix when ms_env installed it. False: nothing of ours there, nothing deleted.

Source code in src/ms_env/recipes.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
def remove(recipe: Recipe, host: Host = LOCAL) -> bool:
    """Delete the prefix when ms_env installed it. False: nothing of ours there, nothing deleted."""
    key = f"{recipe.name}@{host.address or 'local'}"
    with _LOCK:
        current = _INSTALLS.get(key)
        if current is not None and not current.future.done():
            raise RuntimeError(f"{recipe.name} is being installed on {host.address or 'this machine'}.")
    with prefix_lock(recipe.prefix, host):
        if host.address is None:
            _prefix(recipe)
            if not (Path(recipe.prefix, STAMP).is_file() or Path(recipe.prefix + _INSTALLING).is_file()):
                return False
            _delete(recipe.prefix, recipe.prefix + _INSTALLING)
            return True
        script = (
            f'p={_prefix(recipe)}\n[ -f "$p/{STAMP}" ] || [ -f "$p{_INSTALLING}" ] || {{ echo no; exit 0; }}\n'
            f'rm -rf -- "$p" "$p{_INSTALLING}"'
        )
        return host.run(script, timeout=600).decode().strip() != "no"

status

status(recipe: Recipe, host: Host = LOCAL) -> str

READY, MISSING or UNREACHABLE. Blocks like locate, which also says where the tool is.

Source code in src/ms_env/recipes.py
585
586
587
def status(recipe: Recipe, host: Host = LOCAL) -> str:
    """READY, MISSING or UNREACHABLE. Blocks like `locate`, which also says where the tool is."""
    return locate(recipe, host)[0]

verify

verify(recipe: Recipe, host: Host = LOCAL) -> list[str]

What the environment at the recipe's prefix lacks of what the recipe asks for; [] when it meets it.

The way to take an environment the user already has instead of installing one: every pinned conda package (looked up in conda-meta), every pinned pip package (asked to the python of the prefix) and the recipe's check on the executables of that prefix. Reads only. ponytail: a pip URL or path is not looked up, and >= counts as "is there".

Source code in src/ms_env/recipes.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
def verify(recipe: Recipe, host: Host = LOCAL) -> list[str]:
    """What the environment at the recipe's prefix lacks of what the recipe asks for; [] when it meets it.

    The way to take an environment the user already has instead of installing one: every
    pinned conda package (looked up in `conda-meta`), every pinned pip package (asked to the
    python of the prefix) and the recipe's check on the executables of that prefix. Reads
    only. ponytail: a pip URL or path is not looked up, and `>=` counts as "is there".
    """
    conda = []
    for name, version in map(_pin, recipe.conda):
        # conda's `=1.2` takes 1.2 and 1.2.x; a file there is name-version-build.json
        globs = [f"{name}-{version}-*.json", f"{name}-{version}.*-*.json"] if version else [f"{name}-[0-9]*-*.json"]
        conda.append((globs, f"conda: {name}{'=' + version if version else ''} is asked for and is not there"))
    pins = ["==".join(filter(None, _pin(spec))) for spec in recipe.pip if "/" not in spec]
    lacks = (_lacks_here if host.address is None else partial(_lacks_there, host=host))(recipe, conda, pins)
    inside = tuple(path for path in recipe.candidates if path.startswith(recipe.prefix + "/"))
    if recipe.check and status(dataclasses.replace(recipe, candidates=inside, commands=()), host) != READY:
        lacks.append(f"check: `{shlex.join(recipe.check)}` passes for none of {', '.join(inside) or 'its executables'}")
    return lacks

find_environment_manager

find_environment_manager(*extra_variables: str) -> Path | None

The program that creates environments here: micromamba, unless a variable names another.

extra_variables are app-specific overrides, read before MOLSUITE_ENV_MANAGER; any of them may name a conda or a mamba. None: the recipe downloads its own micromamba.

Source code in src/ms_env/steps.py
87
88
89
90
91
92
93
94
95
96
97
98
def find_environment_manager(*extra_variables: str) -> Path | None:
    """The program that creates environments here: micromamba, unless a variable names another.

    ``extra_variables`` are app-specific overrides, read before ``MOLSUITE_ENV_MANAGER``; any
    of them may name a conda or a mamba. None: the recipe downloads its own micromamba.
    """
    named = [str(os.environ.get(variable) or "").strip() for variable in (*extra_variables, "MOLSUITE_ENV_MANAGER")]
    for candidate in (*filter(None, named), shutil.which("micromamba")):
        path = Path(candidate or "").expanduser()
        if path.is_file() and os.access(path, os.X_OK):
            return path.resolve()
    return None

run_step

run_step(step: Step, on_line: Callable[[str], None] | None = None) -> None

Run one step, streaming its output. Raises StepFailed on failure.

Source code in src/ms_env/steps.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def run_step(step: Step, on_line: Callable[[str], None] | None = None) -> None:
    """Run one step, streaming its output. Raises StepFailed on failure."""
    emit = on_line or (lambda _line: None)
    if step.run is not None:
        step.run(emit)
        return
    if step.call is not None:
        message = step.call()
        if message:
            emit(message)
        return
    if not step.argv:
        return
    emit("$ " + " ".join(step.argv))
    try:
        process = subprocess.Popen(
            step.argv,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding="utf-8",  # not the locale's: cp1252 on Windows
            errors="replace",
            bufsize=1,
        )
    except FileNotFoundError as exc:
        raise StepFailed(f"{step.name}: command not found ({exc.filename}).") from exc
    deadline = time.monotonic() + step.timeout
    assert process.stdout is not None
    for line in process.stdout:
        emit(line.rstrip())
        if time.monotonic() > deadline:
            process.kill()
            raise StepFailed(f"{step.name}: timed out after {step.timeout:.0f}s.")
    try:
        code = process.wait(timeout=max(1.0, deadline - time.monotonic()))
    except subprocess.TimeoutExpired:
        process.kill()
        raise StepFailed(f"{step.name}: timed out after {step.timeout:.0f}s.") from None
    if code != 0:
        raise StepFailed(f"{step.name}: exited with code {code}.")

run_steps

run_steps(steps: Iterable[Step], on_line: Callable[[str], None] | None = None, on_step: Callable[[int, Step], None] | None = None) -> None
Source code in src/ms_env/steps.py
76
77
78
79
80
81
82
83
84
def run_steps(
    steps: Iterable[Step],
    on_line: Callable[[str], None] | None = None,
    on_step: Callable[[int, Step], None] | None = None,
) -> None:
    for index, step in enumerate(steps):
        if on_step is not None:
            on_step(index, step)
        run_step(step, on_line)

conda_platform

conda_platform(system: str, machine: str) -> str

linux-64, osx-arm64, win-64...; system-machine for one conda has no name for.

Source code in src/ms_env/host.py
23
24
25
26
def conda_platform(system: str, machine: str) -> str:
    """`linux-64`, `osx-arm64`, `win-64`...; `system-machine` for one conda has no name for."""
    system, machine = system.lower(), machine.lower()
    return _PLATFORMS.get((system, machine), f"{system}-{machine}")

prefix_lock

prefix_lock(prefix: str, host: Host = LOCAL)

Fail closed (Locked) when another client owns this prefix; no background service.

A lock left by a client of this machine that stopped (killed, crashed) is removed and taken again. One of another machine is never guessed at, by age or else, as that is unsafe on a cluster: unlock removes it once its owner is known to have stopped.

Source code in src/ms_env/locking.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@contextmanager
def prefix_lock(prefix: str, host: Host = LOCAL):
    """Fail closed (`Locked`) when another client owns this prefix; no background service.

    A lock left by a client of this machine that stopped (killed, crashed) is removed and taken
    again. One of another machine is never guessed at, by age or else, as that is unsafe on a
    cluster: `unlock` removes it once its owner is known to have stopped.
    """
    if not prefix or Path(prefix) == Path(prefix).parent:
        raise ValueError("a lock requires a dedicated environment prefix")
    owner = json.dumps({"client": socket.gethostname(), "pid": os.getpid(), "started": _started(os.getpid()) or "",
                        "since": time.strftime("%Y-%m-%d %H:%M:%S")})
    lock, held = _take(prefix, host, owner)
    if held is not None and _gone(_owner(held)):
        # ponytail: two clients of this machine that find one stale lock at once can both drop it, and
        # the second then drops the lock the first just took; the owner is checked again right before.
        log.warning("removing the lock of %s left by a client that stopped: %s", prefix, held)
        _drop(lock, host, held)
        lock, held = _take(prefix, host, owner)
    if held is not None:
        raise Locked(prefix, host, lock, _owner(held))
    try:
        yield
    finally:
        _drop(lock, host)

unlock

unlock(prefix: str, host: Host = LOCAL) -> dict

Remove the lock of prefix, whoever took it, and return what its owner wrote ({} for no lock). Only once that owner is known to have stopped: else two clients change one environment.

Source code in src/ms_env/locking.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def unlock(prefix: str, host: Host = LOCAL) -> dict:
    """Remove the lock of `prefix`, whoever took it, and return what its owner wrote ({} for no lock).
    Only once that owner is known to have stopped: else two clients change one environment."""
    if host.address is None:
        lock = _local_lock(prefix)
        if not lock.is_dir():
            return {}
        path = lock / "owner.json"
        held = path.read_text() if path.is_file() else ""
    else:
        said = host.run(_LOCK_SH.format(prefix=shlex.quote(prefix))
                        + '[ -d "$lock" ] || exit 0; printf "%s\\n" "$lock"; cat "$lock/owner.json" 2>/dev/null',
                        timeout=60).decode()
        if not said:
            return {}
        lock, _, held = said.partition("\n")
    _drop(str(lock), host)
    return _owner(held)