errand-lib 2026.11.26.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- errand/__init__.py +81 -0
- errand/__main__.py +5 -0
- errand/_version.py +1 -0
- errand/alone.py +204 -0
- errand/config.py +266 -0
- errand/declared.py +150 -0
- errand/discovery.py +113 -0
- errand/entries.py +348 -0
- errand/held.py +233 -0
- errand/include/errand/require.hpp +149 -0
- errand/include/errand/say.hpp +133 -0
- errand/launcher.py +21 -0
- errand/layers.py +306 -0
- errand/local.py +70 -0
- errand/memos.py +422 -0
- errand/preloaded.py +357 -0
- errand/rows.py +31 -0
- errand/runner.py +211 -0
- errand/servers.py +197 -0
- errand/steps.py +194 -0
- errand_lib-2026.11.26.2.dist-info/METADATA +24 -0
- errand_lib-2026.11.26.2.dist-info/RECORD +24 -0
- errand_lib-2026.11.26.2.dist-info/WHEEL +4 -0
- errand_lib-2026.11.26.2.dist-info/licenses/LICENSE +21 -0
errand/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""errand's Python: what a project declares ( `errand-*.py` ), and what a run written in Python says ( ADR 0032, 0034 ).
|
|
2
|
+
|
|
3
|
+
What launches, waits, carries and records is a program ( `cmd/errand` ); this package is what it asks of Python. A file of
|
|
4
|
+
work imports from here and nothing else, and finding the entries of a tree imports every one of them: the names below are
|
|
5
|
+
standard library only, the declarations are reached lazily.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .entries import ( # noqa: F401 -- the public surface of a file of work
|
|
10
|
+
Args,
|
|
11
|
+
Param,
|
|
12
|
+
bench,
|
|
13
|
+
build_dir,
|
|
14
|
+
cache_dir,
|
|
15
|
+
download,
|
|
16
|
+
entry,
|
|
17
|
+
experiment,
|
|
18
|
+
has_tag,
|
|
19
|
+
library_cache,
|
|
20
|
+
memo,
|
|
21
|
+
out_dir,
|
|
22
|
+
require,
|
|
23
|
+
tag,
|
|
24
|
+
test,
|
|
25
|
+
track,
|
|
26
|
+
)
|
|
27
|
+
from .local import Skipped, have, need, skip, value # noqa: F401
|
|
28
|
+
from .rows import row # noqa: F401
|
|
29
|
+
from .steps import Lin, Log, Static, result, step, view # noqa: F401
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
from ._version import __version__ # written when it is built: the tag of a release, or what git says
|
|
33
|
+
except ImportError:
|
|
34
|
+
__version__ = "0+source"
|
|
35
|
+
|
|
36
|
+
# Read when a default is needed: `errand.default_env = "gpu"` in an `errand-*.py`.
|
|
37
|
+
default_env: str | None = None
|
|
38
|
+
# What a bare `errand run` runs: `errand.default_run = [ "tests/**::*" ]`, targets from the project root.
|
|
39
|
+
default_run: list | None = None
|
|
40
|
+
|
|
41
|
+
_LAZY = {
|
|
42
|
+
"main": "launcher",
|
|
43
|
+
**dict.fromkeys( ( "configure", "Env", "envs", "providers" ), "config" ),
|
|
44
|
+
**dict.fromkeys( ( "serve", "http", "Server", "ServeError" ), "servers" ),
|
|
45
|
+
**dict.fromkeys( ( "runners", "Runner", "Errand", "Pytest", "Catch2", "Cargo", "Python", "Executable" ), "runner" ),
|
|
46
|
+
**dict.fromkeys( ( "Vars", "Venv", "Micromamba", "Conda", "Uv", "Nix", "Guix", "Module", "Apptainer", "Docker", "Podman",
|
|
47
|
+
"Ssh", "Slurm", "Mpi", "Preload", "Missing", "Windows", "WindowsBox" ), "layers" ),
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
__all__ = [ "Args", "Lin", "Log", "Param", "Skipped", "Static", "bench", "build_dir", "cache_dir", "default_env", "default_run", "download", "entry",
|
|
51
|
+
"experiment", "has_tag", "have", "library_cache", "memo", "need", "out_dir", "require", "result", "row", "skip", "step", "tag",
|
|
52
|
+
"test", "track", "value", "view", *_LAZY ]
|
|
53
|
+
|
|
54
|
+
from typing import TYPE_CHECKING
|
|
55
|
+
if TYPE_CHECKING: # the same names, for whoever cannot follow `__getattr__`
|
|
56
|
+
from .config import Env, configure, envs, providers
|
|
57
|
+
from .launcher import main
|
|
58
|
+
from .layers import (
|
|
59
|
+
Apptainer, Conda, Docker, Guix, Micromamba, Missing, Module, Mpi, Nix, Podman, Preload, Slurm, Ssh, Uv, Vars, Venv,
|
|
60
|
+
Windows, WindowsBox,
|
|
61
|
+
)
|
|
62
|
+
from .runner import Cargo, Catch2, Errand, Executable, Pytest, Python, Runner, runners
|
|
63
|
+
from .servers import ServeError, Server, http, serve
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# What a server is comes with the request ( ADR 0040 )
|
|
67
|
+
_GONE = { **dict.fromkeys( ( "services", "Service", "http_json" ), "a server is asked for in full: errand.serve( … ), or errand serve [options] -- COMMAND" ),
|
|
68
|
+
"sources": "errand serve source URL", **dict.fromkeys( ( "dev_sources", "Checkout" ), "errand serve dev REPOSITORY PATH" ) }
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def __getattr__( name ):
|
|
72
|
+
if name in _GONE:
|
|
73
|
+
raise AttributeError( f"errand.{name} is not read any more: {_GONE[ name ]}" )
|
|
74
|
+
if name in _LAZY:
|
|
75
|
+
import importlib
|
|
76
|
+
return getattr( importlib.import_module( f"errand.{_LAZY[ name ]}" ), name )
|
|
77
|
+
raise AttributeError( f"module {__name__!r} has no attribute {name!r}" )
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def __dir__( ):
|
|
81
|
+
return sorted( { *__all__, *globals() } )
|
errand/__main__.py
ADDED
errand/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = '2026.11.26.2'
|
errand/alone.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""What errand's Python does where errand's program is not: the same places, the same files, so that a program finds the same
|
|
2
|
+
things whether errand runs it or not.
|
|
3
|
+
|
|
4
|
+
Only the standard library; nothing here is needed, nor read, where the program is."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import stat
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
ZONE = "errand-cache/downloads" # as the program has it ( ADR 0013 )
|
|
17
|
+
WORK = ".errand-work"
|
|
18
|
+
TAG = "Signature: 8a477f597d28d172789f06886806bc55\n# made by errand: regenerated when missing\n"
|
|
19
|
+
|
|
20
|
+
_said: set = set()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def say( text: str ):
|
|
24
|
+
"""A word to whoever runs the program, once; never its failure."""
|
|
25
|
+
if text in _said or sys.stderr is None:
|
|
26
|
+
return
|
|
27
|
+
_said.add( text )
|
|
28
|
+
try:
|
|
29
|
+
print( text, file = sys.stderr, flush = True )
|
|
30
|
+
except ( OSError, ValueError, UnicodeError, AttributeError ):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def root_or_here() -> Path:
|
|
35
|
+
"""The project's root; here, in a directory nobody declared anything about: a project all the same."""
|
|
36
|
+
from .local import project_root
|
|
37
|
+
said = os.environ.get( "ERRAND_ROOT" )
|
|
38
|
+
if said:
|
|
39
|
+
return Path( said )
|
|
40
|
+
try:
|
|
41
|
+
return project_root()
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
return Path.cwd()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ── the cache of a library ───────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
def can_write( path: Path ) -> bool:
|
|
49
|
+
"""`os.access` lies ( Windows, read-only mounts ): a file is written"""
|
|
50
|
+
try:
|
|
51
|
+
path.mkdir( parents = True, exist_ok = True )
|
|
52
|
+
probe = path / f".write_probe_{os.getpid()}"
|
|
53
|
+
probe.write_text( "ok" )
|
|
54
|
+
probe.unlink()
|
|
55
|
+
return True
|
|
56
|
+
except OSError:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_own( path: Path ) -> bool:
|
|
61
|
+
"""Whether `path`, in a directory everybody writes in, is a directory of this user's that nobody else writes in ( made so when
|
|
62
|
+
it is not there ): what a cache holds is loaded, and run."""
|
|
63
|
+
try:
|
|
64
|
+
path.mkdir( mode = 0o700, exist_ok = True )
|
|
65
|
+
st = path.lstat()
|
|
66
|
+
except OSError:
|
|
67
|
+
return False
|
|
68
|
+
if not hasattr( os, "getuid" ):
|
|
69
|
+
return True
|
|
70
|
+
return stat.S_ISDIR( st.st_mode ) and st.st_uid == os.getuid() and not st.st_mode & 0o022
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def tag( path: Path ) -> Path:
|
|
74
|
+
"""A cache says it is one ( https://bford.info/cachedir/ ): what copies or backs up a tree leaves it alone."""
|
|
75
|
+
try:
|
|
76
|
+
if not ( path / "CACHEDIR.TAG" ).exists():
|
|
77
|
+
( path / "CACHEDIR.TAG" ).write_text( TAG )
|
|
78
|
+
except OSError:
|
|
79
|
+
pass
|
|
80
|
+
return path
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def library_cache( name: str ) -> Path:
|
|
84
|
+
if not name or name in ( ".", ".." ) or any( c in name for c in "/\\" ):
|
|
85
|
+
raise ValueError( f"library_cache( {name!r} ): the name of a library" )
|
|
86
|
+
given = os.environ.get( "ERRAND_CACHES" )
|
|
87
|
+
if given:
|
|
88
|
+
if can_write( Path( given ) / name ):
|
|
89
|
+
return tag( Path( given ) / name )
|
|
90
|
+
say( f"errand: {Path( given ) / name} ( ERRAND_CACHES ) cannot be written: another cache is used for {name}" )
|
|
91
|
+
try:
|
|
92
|
+
home = Path.home()
|
|
93
|
+
except ( RuntimeError, KeyError ): # an account with no home ( a container, a service )
|
|
94
|
+
home = None
|
|
95
|
+
if sys.platform == "darwin":
|
|
96
|
+
own = home / "Library" / "Caches" / name if home else None
|
|
97
|
+
elif os.name == "nt":
|
|
98
|
+
base = os.environ.get( "LOCALAPPDATA" ) or ( str( home / "AppData" / "Local" ) if home else None )
|
|
99
|
+
own = Path( base ) / name / "cache" if base else None
|
|
100
|
+
else:
|
|
101
|
+
base = os.environ.get( "XDG_CACHE_HOME" )
|
|
102
|
+
own = Path( base ) / name if base else home / ".cache" / name if home else None
|
|
103
|
+
if own and can_write( own ):
|
|
104
|
+
return tag( own )
|
|
105
|
+
last = Path( tempfile.gettempdir() ) / f"{name}-cache-{os.getuid() if hasattr( os, 'getuid' ) else 'shared'}"
|
|
106
|
+
if is_own( last ) and can_write( last ):
|
|
107
|
+
return tag( last )
|
|
108
|
+
raise RuntimeError( f"errand: no cache directory for {name} can be written ( {own or 'no home directory'}, {last} )" )
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ── a file at a URL ──────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
def name_of( url: str ) -> str:
|
|
114
|
+
from urllib.parse import unquote, urlparse
|
|
115
|
+
name = unquote( urlparse( url ).path.rstrip( "/" ).rsplit( "/", 1 )[ -1 ] )
|
|
116
|
+
name = "".join( c if c.isascii() and c.isalnum() or c in "._-+" or ord( c ) > 127 else "_" for c in name ).lstrip( "." )
|
|
117
|
+
return name or "download"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def download( url: str, sha256: str | None, name: str | None, root ) -> Path:
|
|
121
|
+
"""As the program does: the file under its hash, one fetch of a URL at a time, whole or not there. With no way to the URL,
|
|
122
|
+
nobody is asked: an error."""
|
|
123
|
+
sha256 = sha256.lower() if sha256 else None
|
|
124
|
+
d = Path( root ) / ZONE
|
|
125
|
+
key = hashlib.sha256( url.encode() ).hexdigest()[ :32 ]
|
|
126
|
+
name = name or name_of( url )
|
|
127
|
+
if name in ( ".", ".." ) or any( c in name for c in "/\\" ):
|
|
128
|
+
raise ValueError( f"download( {url!r}, name = {name!r} ): the name of a file" )
|
|
129
|
+
index = d / "by-url" / f"{key}.json"
|
|
130
|
+
|
|
131
|
+
def have():
|
|
132
|
+
sha, called = sha256, name
|
|
133
|
+
if not sha:
|
|
134
|
+
try:
|
|
135
|
+
got = json.loads( index.read_text() )
|
|
136
|
+
sha, called = str( got[ "sha256" ] ), str( got.get( "name" ) or name )
|
|
137
|
+
except ( OSError, ValueError, KeyError, TypeError ):
|
|
138
|
+
return None
|
|
139
|
+
p = d / sha / called
|
|
140
|
+
return p if p.is_file() else None
|
|
141
|
+
|
|
142
|
+
found = have()
|
|
143
|
+
if found:
|
|
144
|
+
return found
|
|
145
|
+
if os.environ.get( "ERRAND_NO_INTERNET" ) and not url.startswith( "file:" ):
|
|
146
|
+
raise RuntimeError( f"{url}: this place is said to have no way out ( ERRAND_NO_INTERNET ), and errand is not here to ask" )
|
|
147
|
+
lock = d / WORK / "locks" / key
|
|
148
|
+
lock.parent.mkdir( parents = True, exist_ok = True )
|
|
149
|
+
while True:
|
|
150
|
+
try:
|
|
151
|
+
lock.mkdir()
|
|
152
|
+
break
|
|
153
|
+
except FileExistsError:
|
|
154
|
+
try:
|
|
155
|
+
if time.time() - lock.stat().st_mtime > 3600: # of a run that died
|
|
156
|
+
lock.rmdir()
|
|
157
|
+
continue
|
|
158
|
+
except OSError:
|
|
159
|
+
continue
|
|
160
|
+
time.sleep( 0.2 )
|
|
161
|
+
part = d / WORK / "parts" / f"{name}.{os.getpid()}.{time.time_ns()}"
|
|
162
|
+
try:
|
|
163
|
+
found = have() # the one that was waited for
|
|
164
|
+
if found:
|
|
165
|
+
return found
|
|
166
|
+
part.parent.mkdir( parents = True, exist_ok = True )
|
|
167
|
+
h, size = hashlib.sha256(), 0
|
|
168
|
+
from urllib.error import URLError
|
|
169
|
+
from urllib.request import Request, urlopen
|
|
170
|
+
try:
|
|
171
|
+
with urlopen( Request( url, headers = { "User-Agent": "errand" } ), timeout = 60 ) as r, open( part, "wb" ) as f:
|
|
172
|
+
want = r.headers.get( "Content-Length" )
|
|
173
|
+
while True:
|
|
174
|
+
chunk = r.read( 1 << 20 )
|
|
175
|
+
if not chunk:
|
|
176
|
+
break
|
|
177
|
+
f.write( chunk )
|
|
178
|
+
h.update( chunk )
|
|
179
|
+
size += len( chunk )
|
|
180
|
+
except URLError as err: # ( its refusals, `HTTPError`, among them )
|
|
181
|
+
raise RuntimeError( f"{url}: {getattr( err, 'code', '' ) or ''} {err.reason}".replace( ": ", ": " ) ) from None
|
|
182
|
+
except ( OSError, ValueError ) as err:
|
|
183
|
+
raise RuntimeError( f"{url}: {err}" ) from None
|
|
184
|
+
if want and want.isdigit() and int( want ) != size:
|
|
185
|
+
raise RuntimeError( f"{url}: cut after {size} bytes of {want}" )
|
|
186
|
+
digest = h.hexdigest()
|
|
187
|
+
if sha256 and digest != sha256:
|
|
188
|
+
raise RuntimeError( f"{url}: its sha256 is {digest}, not {sha256} as asked -- removed" )
|
|
189
|
+
( d / digest ).mkdir( parents = True, exist_ok = True )
|
|
190
|
+
os.replace( part, d / digest / name )
|
|
191
|
+
index.parent.mkdir( parents = True, exist_ok = True )
|
|
192
|
+
tmp = index.with_name( f".{index.name}.{os.getpid()}.part" )
|
|
193
|
+
tmp.write_text( json.dumps( { "url": url, "sha256": digest, "name": name } ) )
|
|
194
|
+
os.replace( tmp, index )
|
|
195
|
+
return d / digest / name
|
|
196
|
+
finally:
|
|
197
|
+
try:
|
|
198
|
+
part.unlink()
|
|
199
|
+
except OSError:
|
|
200
|
+
pass
|
|
201
|
+
try:
|
|
202
|
+
lock.rmdir()
|
|
203
|
+
except OSError:
|
|
204
|
+
pass
|
errand/config.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""`errand-*.py`: what a project declares, held as it is read.
|
|
2
|
+
|
|
3
|
+
Ordinary Python, loaded once BY PATH, under private names: loading one can never be what shadows the package it imports from.
|
|
4
|
+
There is no entry point to call and nothing to return: `configure`, `envs` and `runners` hold what they are given.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import dataclasses
|
|
9
|
+
import hashlib
|
|
10
|
+
import importlib
|
|
11
|
+
import importlib.util
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
import types
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import layers as L, local, runner
|
|
20
|
+
from .runner import check_zones
|
|
21
|
+
|
|
22
|
+
CONFIG_GLOB = "errand-*.py" # every one at the root is read; the root is the nearest directory that has one
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def config_files( directory: Path ) -> list:
|
|
26
|
+
"""The project files in `directory`, in the order they are read: `errand-vars.py` first, so that the files declaring
|
|
27
|
+
environments can ask it for the hosts and paths of this machine."""
|
|
28
|
+
return sorted( ( p for p in directory.glob( CONFIG_GLOB ) if p.is_file() ), key = lambda p: ( p.name != local.VARS_FILE, p.name ) )
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ── an environment ───────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
NEEDS = ( "cpus", "ram", "gpus", "gpu_ram", "exclusive" )
|
|
34
|
+
_SIZE = re.compile( r"\s*\d+(\.\d+)?\s*[KMGT]?B?\s*", re.I )
|
|
35
|
+
_SHARE = re.compile( r"\s*\d+(\.\d+)?\s*%\s*" )
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _check_need( name, v ):
|
|
39
|
+
if name not in NEEDS:
|
|
40
|
+
raise ValueError( f"needs[ {name!r} ]: one of {', '.join( NEEDS )}" )
|
|
41
|
+
text = str( v )
|
|
42
|
+
fits = isinstance( v, bool ) if name == "exclusive" else v is None or ( _SIZE.fullmatch( text ) if name.endswith( "ram" ) else
|
|
43
|
+
re.fullmatch( r"\d+(\.\d+)?", text ) ) \
|
|
44
|
+
or name == "gpu_ram" and _SHARE.fullmatch( text )
|
|
45
|
+
if not fits:
|
|
46
|
+
raise ValueError( f"needs[ {name!r} ] = {v!r}: not a { 'size ( 16G )' if name == 'ram' else 'size or a share ( 40G, 75% )' if name == 'gpu_ram' else 'number' if name != 'exclusive' else 'truth' }" )
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Env:
|
|
50
|
+
"""Where work runs: a stack of layers, and the tags saying what it is.
|
|
51
|
+
|
|
52
|
+
errand.envs[ "gpu" ] = errand.Env( [ errand.Apptainer( ... ) ], driver = "cuda" )
|
|
53
|
+
|
|
54
|
+
The preparation ( setting up, building ) goes through the same layers, unless `prepare` gives it its own: another
|
|
55
|
+
allocation, another machine. Copy what both share:
|
|
56
|
+
|
|
57
|
+
base = [ errand.Ssh( host = "login.hpc", root = "/scratch/me/proj" ) ]
|
|
58
|
+
errand.Env( base + [ errand.Slurm( gpus = 1 ) ], prepare = base + [ errand.Slurm( cpus = 16 ) ] )
|
|
59
|
+
|
|
60
|
+
`tools` names what the runners start in this environment, where its usual name is wrong: `{ "python": "python3.12" }`.
|
|
61
|
+
`needs` is what every run in it takes of the machine, known before anything starts ( ADR 0014 ): `{ "gpus": 1, "gpu_ram":
|
|
62
|
+
"75%", "ram": "16G" }`; the command line is over it. The name is the key it is stored under."""
|
|
63
|
+
|
|
64
|
+
def __init__( self, stack = ( ), prepare = None, tools = None, needs = None, **tags ):
|
|
65
|
+
for k, v in tags.items():
|
|
66
|
+
if isinstance( v, str ) and "," in v:
|
|
67
|
+
raise ValueError( f"tag {k} = {v!r}: a tag value cannot hold a comma, which means several values on the command line" )
|
|
68
|
+
self.name = ""
|
|
69
|
+
self.stack = list( stack )
|
|
70
|
+
self.prepare = None if prepare is None else list( prepare )
|
|
71
|
+
self.tags = dict( tags )
|
|
72
|
+
self.tools = dict( tools or { } )
|
|
73
|
+
self.needs = dict( needs or { } )
|
|
74
|
+
for name, v in self.needs.items():
|
|
75
|
+
_check_need( name, v )
|
|
76
|
+
for name, argv in self.tools.items():
|
|
77
|
+
if not isinstance( argv, ( str, list, tuple ) ) or not argv:
|
|
78
|
+
raise ValueError( f"tools[ {name!r} ]: a command, as a string or a list of words" )
|
|
79
|
+
check_stack( self.stack )
|
|
80
|
+
if self.prepare is not None:
|
|
81
|
+
check_stack( self.prepare, " ( in `prepare` )" )
|
|
82
|
+
if L.first( self.stack, L.Windows ) != L.first( self.prepare, L.Windows ):
|
|
83
|
+
raise ValueError( "`prepare` and the run boot different machines: one errand boots is the same for both -- copy the first layer" )
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def ssh( self ):
|
|
87
|
+
return L.ssh_of( self.stack )
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def vm( self ):
|
|
91
|
+
return L.vm_of( self.stack )
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def container( self ):
|
|
95
|
+
return L.container_of( self.stack )
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def missing( self ):
|
|
99
|
+
"""The `Missing` layer that says why this environment cannot be reached from here, or None."""
|
|
100
|
+
return L.missing_of( [ *self.stack, *( self.prepare or ( ) ) ] )
|
|
101
|
+
|
|
102
|
+
def __repr__( self ):
|
|
103
|
+
return f"Env( {self.name!r}, {self.stack!r} )"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def check_stack( stack, where = "" ):
|
|
107
|
+
"""What a stack must look like: said where it is written, not on the day somebody first runs in it."""
|
|
108
|
+
for i, layer in enumerate( stack ):
|
|
109
|
+
kind = type( layer ).__name__
|
|
110
|
+
if isinstance( layer, L.Ssh ) and i:
|
|
111
|
+
raise ValueError( f"Ssh must be the first layer{where}" )
|
|
112
|
+
if isinstance( layer, ( L.Windows, L.WindowsBox ) ) and i and not ( i == 1 and isinstance( stack[ 0 ], L.Ssh ) ):
|
|
113
|
+
raise ValueError( f"{kind} must be the first layer, or follow its Ssh{where}" )
|
|
114
|
+
if isinstance( layer, L.WindowsBox ) and not i:
|
|
115
|
+
raise ValueError( f"WindowsBox must follow the Ssh that reaches the machine{where}" )
|
|
116
|
+
if isinstance( layer, L.Container ) and not getattr( layer, "image", "x" ):
|
|
117
|
+
raise ValueError( f"{kind}( image = ... ) is empty: name the image" )
|
|
118
|
+
if isinstance( layer, L.Micromamba ) and not layer.name:
|
|
119
|
+
raise ValueError( f"{kind}( name = ... ) is empty: name the environment" )
|
|
120
|
+
if sum( isinstance( l, L.Slurm ) for l in stack ) > 1:
|
|
121
|
+
raise ValueError( f"several schedulers{where}: one allocation per list; to prepare in another one, give it its own "
|
|
122
|
+
f"layers: Env( [ ... ], prepare = [ ... ] )" )
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Envs( dict ):
|
|
126
|
+
"""`errand.envs[ "name" ] = errand.Env( ... )`: the key becomes the environment's name."""
|
|
127
|
+
|
|
128
|
+
def __setitem__( self, name, env ):
|
|
129
|
+
if not isinstance( env, Env ):
|
|
130
|
+
raise TypeError( f"envs[ {name!r} ] must be an errand.Env, not {type( env ).__name__}" )
|
|
131
|
+
if "," in name:
|
|
132
|
+
raise ValueError( f"envs[ {name!r} ]: an environment name cannot hold a comma, which means several on the command line" )
|
|
133
|
+
env.name = name
|
|
134
|
+
super().__setitem__( name, env )
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ── a project's settings ─────────────────────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
@dataclass
|
|
140
|
+
class Settings:
|
|
141
|
+
# Where the project's own code is, from its root, put in front of any other checkout of it ( `src` when there is one )
|
|
142
|
+
src : list = field( default_factory = list )
|
|
143
|
+
# Directories a target never walks into: vendored code, fixtures
|
|
144
|
+
exclude: list = field( default_factory = list )
|
|
145
|
+
# Where what is built goes, one directory per environment under it: two never share a binary. None: in errand's caches for
|
|
146
|
+
# the project ( `errand.build_dir`, ADR 0039 ), which keeps them tidy; a path from the root: the project's to tidy
|
|
147
|
+
build : str | None = None
|
|
148
|
+
# Everything errand writes for this project ( `runs/`, `builds/`, `state/` ), from its root, or absolute.
|
|
149
|
+
# `$ERRAND_OUTPUTS_DIR` wins; over there, `Ssh( errand_outputs_directory = ... )`.
|
|
150
|
+
outputs_directory: str = "errand-outputs"
|
|
151
|
+
# What errand builds ( `builds/` above ) somewhere else: another disk, or one directory several projects share
|
|
152
|
+
builds_directory : str | None = None
|
|
153
|
+
# Where a run writes in the project's copy over there ( ADR 0006 ). `{ "results": "back" }`: path patterns ( `results`, a
|
|
154
|
+
# name anywhere; `/results`, at the root ), each a kind -- `back`, written there and brought back; `build`, built there;
|
|
155
|
+
# `cache`, added to on both sides, never replaced nor deleted ( ADR 0012 ). A path may name `{env}` or `{build_dir}`.
|
|
156
|
+
zones : dict = field( default_factory = dict )
|
|
157
|
+
# How `errand run` draws a run's output ( ADR 0016 ): behind a `bar`, behind `spaces`, or `off`; `plain`: no colors
|
|
158
|
+
output : str = "bar"
|
|
159
|
+
# Each run's page opened in the browser as it starts ( ADR 0017 §5 )
|
|
160
|
+
open : bool = False
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def configure( **kw ):
|
|
164
|
+
"""Project-wide settings: the fields of `Settings`."""
|
|
165
|
+
for k, v in kw.items():
|
|
166
|
+
if not hasattr( settings, k ):
|
|
167
|
+
raise TypeError( f"configure(): unknown setting {k!r}; expected one of {', '.join( vars( settings ) )}" )
|
|
168
|
+
if k == "zones":
|
|
169
|
+
check_zones( v, "configure( zones = ... )" )
|
|
170
|
+
if k == "output" and v not in ( "bar", "spaces", "off", "plain" ):
|
|
171
|
+
raise ValueError( f"configure( output = {v!r} ): bar, spaces, off or plain" )
|
|
172
|
+
setattr( settings, k, v )
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
settings = Settings()
|
|
176
|
+
envs = Envs()
|
|
177
|
+
# What declares environments before the project does: functions of the project's root that fill `envs`. An installed package
|
|
178
|
+
# declares one under the entry point group `errand.envs`. They run after `errand-vars.py`, and before the project's other
|
|
179
|
+
# files, which can then redefine what they declared. One that reads files of its own answers their paths: a document kept of
|
|
180
|
+
# the project is made again when one changes. `$ERRAND_PROVIDERS` ( `module:function`, separated by commas ) names more, for a
|
|
181
|
+
# package that is on the path without being installed.
|
|
182
|
+
providers = [ ]
|
|
183
|
+
GROUP = "errand.envs"
|
|
184
|
+
NAMED = "ERRAND_PROVIDERS"
|
|
185
|
+
read_too: list = [ ] # the files the providers read
|
|
186
|
+
provided: set = set() # id() of the environments a provider declared: never the default
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def reset( ):
|
|
190
|
+
for f in dataclasses.fields( Settings ):
|
|
191
|
+
setattr( settings, f.name, getattr( Settings(), f.name ) )
|
|
192
|
+
errand = sys.modules[ "errand" ]
|
|
193
|
+
errand.default_env = errand.default_run = None
|
|
194
|
+
envs.clear()
|
|
195
|
+
provided.clear()
|
|
196
|
+
read_too.clear()
|
|
197
|
+
runner.reset()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def load( root: Path ) -> bool:
|
|
201
|
+
"""Read the project's files, if there are any -> were there? Each one's plain values are offered to the files after it,
|
|
202
|
+
and to entries ( `errand.value`, `errand.need` )."""
|
|
203
|
+
root = Path( root )
|
|
204
|
+
reset()
|
|
205
|
+
files = config_files( root )
|
|
206
|
+
local.reset( files, root )
|
|
207
|
+
package, asked = _package( root ), False
|
|
208
|
+
for path in files:
|
|
209
|
+
if not asked and path.name != local.VARS_FILE:
|
|
210
|
+
_provide( root )
|
|
211
|
+
asked = True
|
|
212
|
+
spec = importlib.util.spec_from_file_location( f"{package}._errand_" + re.sub( r"\W", "_", path.stem ), path )
|
|
213
|
+
module = importlib.util.module_from_spec( spec )
|
|
214
|
+
spec.loader.exec_module( module )
|
|
215
|
+
local.offer( module )
|
|
216
|
+
if not asked:
|
|
217
|
+
_provide( root )
|
|
218
|
+
return bool( files )
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _package( root: Path ) -> str:
|
|
222
|
+
"""A private package whose directory is the root: `from .helpers import X` in a project file reads `helpers.py` beside it,
|
|
223
|
+
and nothing is put on `sys.path`."""
|
|
224
|
+
name = "_errand_root_" + hashlib.sha1( str( root.resolve() ).encode() ).hexdigest()[ :12 ]
|
|
225
|
+
for key in [ k for k in sys.modules if k == name or k.startswith( name + "." ) ]:
|
|
226
|
+
del sys.modules[ key ]
|
|
227
|
+
package = types.ModuleType( name )
|
|
228
|
+
package.__path__ = [ str( root ) ]
|
|
229
|
+
sys.modules[ name ] = package
|
|
230
|
+
return name
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _provide( root: Path ):
|
|
234
|
+
"""The providers, then those installed packages declare. One that fails is said and skipped."""
|
|
235
|
+
def say( text ):
|
|
236
|
+
print( f"errand: {text}", file = sys.stderr )
|
|
237
|
+
found = list( providers )
|
|
238
|
+
for name in filter( None, ( n.strip() for n in os.environ.get( NAMED, "" ).split( "," ) ) ):
|
|
239
|
+
module, _, attr = name.partition( ":" )
|
|
240
|
+
try:
|
|
241
|
+
fn = getattr( importlib.import_module( module ), attr or "provide" )
|
|
242
|
+
except Exception as err:
|
|
243
|
+
say( f"the environments of `{name}` ( ${NAMED} ) are not loaded: {err}" )
|
|
244
|
+
continue
|
|
245
|
+
if fn not in found:
|
|
246
|
+
found.append( fn )
|
|
247
|
+
try:
|
|
248
|
+
from importlib.metadata import entry_points
|
|
249
|
+
installed = entry_points( group = GROUP ) if sys.version_info >= ( 3, 10 ) else entry_points().get( GROUP, ( ) )
|
|
250
|
+
except Exception:
|
|
251
|
+
installed = ( )
|
|
252
|
+
for ep in installed:
|
|
253
|
+
try:
|
|
254
|
+
fn = ep.load()
|
|
255
|
+
except Exception as err:
|
|
256
|
+
say( f"the environments of `{ep.value}` ( entry point {GROUP} ) are not loaded: {err}" )
|
|
257
|
+
continue
|
|
258
|
+
if fn not in found:
|
|
259
|
+
found.append( fn )
|
|
260
|
+
for fn in found:
|
|
261
|
+
before = set( map( id, envs.values() ) )
|
|
262
|
+
try:
|
|
263
|
+
read_too.extend( Path( p ) for p in fn( root ) or ( ) )
|
|
264
|
+
except Exception as err:
|
|
265
|
+
say( f"`{getattr( fn, '__module__', '' )}.{getattr( fn, '__qualname__', fn )}` failed to declare its environments: {err}" )
|
|
266
|
+
provided.update( id( e ) for e in envs.values() if id( e ) not in before )
|