zelpi-kit 0.1.0__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.
- zelpi_kit/__init__.py +3 -0
- zelpi_kit/__main__.py +5 -0
- zelpi_kit/cli.py +282 -0
- zelpi_kit/env.py +218 -0
- zelpi_kit/install.py +350 -0
- zelpi_kit/net.py +151 -0
- zelpi_kit/run.py +59 -0
- zelpi_kit/store.py +293 -0
- zelpi_kit/wheel.py +164 -0
- zelpi_kit-0.1.0.dist-info/METADATA +58 -0
- zelpi_kit-0.1.0.dist-info/RECORD +14 -0
- zelpi_kit-0.1.0.dist-info/WHEEL +5 -0
- zelpi_kit-0.1.0.dist-info/entry_points.txt +2 -0
- zelpi_kit-0.1.0.dist-info/top_level.txt +1 -0
zelpi_kit/__init__.py
ADDED
zelpi_kit/__main__.py
ADDED
zelpi_kit/cli.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Command line. `run` is parsed by hand so its arguments reach the agent untouched."""
|
|
2
|
+
import argparse
|
|
3
|
+
import getpass
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from . import SITE, __version__, env, install, net, run as runmod, store, wheel
|
|
9
|
+
from .store import KitError, redact
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def out(msg=""):
|
|
13
|
+
print(msg, flush=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_token():
|
|
17
|
+
if sys.stdin is not None and sys.stdin.isatty():
|
|
18
|
+
return getpass.getpass("Download token (hidden): ").strip()
|
|
19
|
+
return sys.stdin.readline().strip()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def cmd_login(a):
|
|
23
|
+
net.check_site(a.site)
|
|
24
|
+
out("Create a download token on the Keys page: %s/keys" % a.site.rstrip("/"))
|
|
25
|
+
token = read_token()
|
|
26
|
+
if token.startswith("zk_live_"):
|
|
27
|
+
raise KitError("that is a robot key (zk_live_...), not a download token: robot keys are never used here")
|
|
28
|
+
if not store.TOKEN_RE.fullmatch(token):
|
|
29
|
+
raise KitError("that does not look like a download token (zk_dl_...)")
|
|
30
|
+
cat = net.get_json(a.site, token, "/v1/kits") # a bad token stops here, nothing is stored
|
|
31
|
+
store.save_token(a.site.rstrip("/"), token)
|
|
32
|
+
store.save_catalogue(cat)
|
|
33
|
+
out("logged in as %s on %s" % (cat.get("email", "?"), a.site))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cmd_logout(a):
|
|
37
|
+
site, token = store.load_token()
|
|
38
|
+
msg = None
|
|
39
|
+
try:
|
|
40
|
+
net.get_json(site, token, "/v1/download-token/revoke", method="POST")
|
|
41
|
+
except KitError as e:
|
|
42
|
+
msg = str(e)
|
|
43
|
+
os.unlink(store.token_path())
|
|
44
|
+
if msg:
|
|
45
|
+
out("local token removed, but it was NOT revoked on the site (%s): revoke it on the Keys page." % msg)
|
|
46
|
+
return 1
|
|
47
|
+
out("logged out; the token was revoked on the site")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_whoami(a):
|
|
51
|
+
site, token = store.load_token()
|
|
52
|
+
try:
|
|
53
|
+
cat = net.get_json(site, token, "/v1/kits")
|
|
54
|
+
out("%s on %s" % (cat.get("email", "?"), site))
|
|
55
|
+
except net.Unreachable as e:
|
|
56
|
+
out("site %s (offline: %s)" % (site, e))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _catalogue_or_none(site, token):
|
|
60
|
+
try:
|
|
61
|
+
return install.fetch_catalogue(site, token)
|
|
62
|
+
except net.Unreachable as e:
|
|
63
|
+
out("(offline: %s)" % e)
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cmd_list(a):
|
|
68
|
+
site, token = store.load_token() if _logged_in() else (None, None)
|
|
69
|
+
cat = _catalogue_or_none(site, token) if site else None
|
|
70
|
+
shown = set()
|
|
71
|
+
for raw in (cat or {}).get("kits", []):
|
|
72
|
+
k = install.clean_kit(raw) if isinstance(raw, dict) else None
|
|
73
|
+
if k:
|
|
74
|
+
cur = store.read_current_safe(k["short"])
|
|
75
|
+
shown.add(k["short"])
|
|
76
|
+
out("%-8s %-12s latest %-8s installed %s" % (k["short"], k["kind"], k["latest"] or "-", cur["version"] if cur else "-"))
|
|
77
|
+
for s in store.installed_shorts():
|
|
78
|
+
if s not in shown:
|
|
79
|
+
cur = store.read_current_safe(s)
|
|
80
|
+
out("%-8s installed %s" % (s, cur["version"] if cur else "-"))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _logged_in():
|
|
84
|
+
return os.path.exists(store.token_path())
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def cmd_versions(a):
|
|
88
|
+
cur = store.read_current_safe(a.short) or {}
|
|
89
|
+
inst = store.installed_versions(a.short)
|
|
90
|
+
avail = {}
|
|
91
|
+
if _logged_in():
|
|
92
|
+
site, token = store.load_token()
|
|
93
|
+
cat = _catalogue_or_none(site, token)
|
|
94
|
+
if cat:
|
|
95
|
+
k = install.find_kit(cat, a.short)
|
|
96
|
+
avail = k["versions"]
|
|
97
|
+
for v in avail:
|
|
98
|
+
why = install.unusable(k, v)
|
|
99
|
+
avail[v] = ("latest " if v == k["latest"] else "") + (why or "")
|
|
100
|
+
names = sorted(set(inst) | set(avail), key=store.vt)
|
|
101
|
+
if not names:
|
|
102
|
+
out("nothing known for %s" % a.short)
|
|
103
|
+
for v in names:
|
|
104
|
+
tags = [t for t, on in (("installed", v in inst), ("CURRENT", v == cur.get("version")),
|
|
105
|
+
("previous", v == cur.get("previous"))) if on]
|
|
106
|
+
out("%s %s %s" % (v, ",".join(tags) or "-", avail.get(v, "").strip()))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _split_spec(spec):
|
|
110
|
+
short, _, ver = spec.partition("==")
|
|
111
|
+
if not store.SHORT_RE.match(short) or (ver and not store.VER_RE.match(ver)):
|
|
112
|
+
raise KitError("expected <short> or <short>==X.Y.Z (e.g. b601 or b601==1.2.0), got %r" % spec)
|
|
113
|
+
return short, ver or None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cmd_install(a):
|
|
117
|
+
short, ver = _split_spec(a.spec)
|
|
118
|
+
site, token = store.load_token()
|
|
119
|
+
v, kj = install.install(site, token, short, ver, deps=not a.no_deps)
|
|
120
|
+
out("installed %s %s; run it with: zelpi-kit run %s <command>" % (short, v, short))
|
|
121
|
+
install.notice_recheck(kj, short, v)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_update(a):
|
|
125
|
+
site, token = store.load_token()
|
|
126
|
+
shorts = [a.short] if a.short else store.installed_shorts()
|
|
127
|
+
if not shorts:
|
|
128
|
+
raise KitError("nothing is installed: run 'zelpi-kit install <robot>'")
|
|
129
|
+
bad = 0
|
|
130
|
+
for s in shorts:
|
|
131
|
+
try:
|
|
132
|
+
install.update(site, token, s)
|
|
133
|
+
except KitError as e:
|
|
134
|
+
sys.stderr.write("zelpi-kit: %s: %s\n" % (s, redact(e, token)))
|
|
135
|
+
bad = 1
|
|
136
|
+
return bad
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def cmd_rollback(a):
|
|
140
|
+
install.rollback(a.short)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_uninstall(a):
|
|
144
|
+
short, ver = _split_spec(a.spec)
|
|
145
|
+
install.uninstall(short, ver)
|
|
146
|
+
out("uninstalled %s%s" % (short, " " + ver if ver else ""))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def cmd_cleanup(a):
|
|
150
|
+
for s in [a.short] if a.short else store.installed_shorts():
|
|
151
|
+
install.cleanup(s)
|
|
152
|
+
out("cleanup done")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def cmd_doctor(a):
|
|
156
|
+
bad = [0]
|
|
157
|
+
|
|
158
|
+
def line(level, msg):
|
|
159
|
+
out("%-5s %s" % (level, msg))
|
|
160
|
+
bad[0] += level == "FAIL"
|
|
161
|
+
|
|
162
|
+
line("ok", "zelpi-kit %s, python %s, home %s" % (__version__, sys.version.split()[0], store.home()))
|
|
163
|
+
if os.path.exists(store.home()):
|
|
164
|
+
try:
|
|
165
|
+
probe = store.p(".doctor-%d" % os.getpid())
|
|
166
|
+
open(probe, "w").close()
|
|
167
|
+
os.unlink(probe)
|
|
168
|
+
except OSError as e:
|
|
169
|
+
line("WARN", "home is not writable (%s): install/update will fail; run still works" % (e.strerror or e))
|
|
170
|
+
line("ok" if env._uv() else "info", "uv: %s" % (env._uv() or "not found (venv + pip will be used)"))
|
|
171
|
+
token = site = None
|
|
172
|
+
if not _logged_in():
|
|
173
|
+
line("WARN", "not logged in")
|
|
174
|
+
else:
|
|
175
|
+
site, token = store.load_token()
|
|
176
|
+
if os.name != "nt" and os.stat(store.token_path()).st_mode & 0o077:
|
|
177
|
+
line("WARN", "the token file is readable by others: chmod 600 %s" % store.token_path())
|
|
178
|
+
try:
|
|
179
|
+
cat = net.get_json(site, token, "/v1/kits")
|
|
180
|
+
line("ok", "site %s accepts the token (%s)" % (site, cat.get("email", "?")))
|
|
181
|
+
st = cat.get("server_time")
|
|
182
|
+
if isinstance(st, (int, float)) and abs(st - time.time()) > 300:
|
|
183
|
+
line("WARN", "this computer's clock differs from the site's by %d s" % abs(st - time.time()))
|
|
184
|
+
except net.Unreachable as e:
|
|
185
|
+
line("WARN", "site unreachable: %s" % e)
|
|
186
|
+
except KitError as e:
|
|
187
|
+
line("FAIL", str(e))
|
|
188
|
+
for s in store.installed_shorts():
|
|
189
|
+
try:
|
|
190
|
+
cur = store.read_current(s)
|
|
191
|
+
except KitError as e:
|
|
192
|
+
line("FAIL", str(e))
|
|
193
|
+
continue
|
|
194
|
+
if not cur:
|
|
195
|
+
line("WARN", "%s: no current version" % s)
|
|
196
|
+
continue
|
|
197
|
+
v = cur["version"]
|
|
198
|
+
vroot, envp = store.version_dir(s, v), store.env_dir(cur["env"])
|
|
199
|
+
try:
|
|
200
|
+
wheel.verify_record(vroot, s, v, strict=False)
|
|
201
|
+
line("ok", "%s %s files match RECORD" % (s, v))
|
|
202
|
+
except (KitError, OSError) as e:
|
|
203
|
+
line("FAIL", "%s %s: %s" % (s, v, e))
|
|
204
|
+
py = env.env_python(envp)
|
|
205
|
+
if os.path.exists(os.path.join(envp, env.MARKER)) and env._probe(py):
|
|
206
|
+
line("ok", "%s environment %s works" % (s, cur["env"]))
|
|
207
|
+
else:
|
|
208
|
+
line("FAIL", "%s environment %s is missing or incomplete: reinstall" % (s, cur["env"]))
|
|
209
|
+
if store.is_running(s, v):
|
|
210
|
+
line("info", "%s %s is running now" % (s, v))
|
|
211
|
+
k = store.cached_kit(s)
|
|
212
|
+
if k and (v in (k.get("deny") or []) or vt_lt(v, k.get("min_version"))):
|
|
213
|
+
line("WARN", "%s %s is denied or below the minimum on the site: update" % (s, v))
|
|
214
|
+
return 1 if bad[0] else 0
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def vt_lt(v, m):
|
|
218
|
+
return bool(m) and store.vt(v) < store.vt(m)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def build_parser():
|
|
222
|
+
ap = argparse.ArgumentParser(prog="zelpi-kit", description="Install and run ZELPI robot kits. "
|
|
223
|
+
"'zelpi-kit run <robot> <command> [args...]' starts a kit command (arguments pass through).")
|
|
224
|
+
ap.add_argument("--version", action="version", version="zelpi-kit " + __version__)
|
|
225
|
+
sub = ap.add_subparsers(dest="cmd", metavar="command")
|
|
226
|
+
|
|
227
|
+
def add(name, fn, help_):
|
|
228
|
+
sp = sub.add_parser(name, help=help_)
|
|
229
|
+
sp.set_defaults(fn=fn)
|
|
230
|
+
return sp
|
|
231
|
+
|
|
232
|
+
add("login", cmd_login, "store a download token (read from the terminal or one stdin line, never argv)") \
|
|
233
|
+
.add_argument("--site", default=SITE)
|
|
234
|
+
add("logout", cmd_logout, "revoke and forget the token")
|
|
235
|
+
add("whoami", cmd_whoami, "who the token belongs to")
|
|
236
|
+
add("list", cmd_list, "robot kits you can install, and what is installed")
|
|
237
|
+
add("install", cmd_install, "install <robot>[==X.Y.Z]").add_argument("spec")
|
|
238
|
+
sub.choices["install"].add_argument("--no-deps", action="store_true", help="skip the dependency install")
|
|
239
|
+
add("update", cmd_update, "move to the latest version (never downgrades)").add_argument("short", nargs="?")
|
|
240
|
+
add("rollback", cmd_rollback, "switch back to the previous version").add_argument("short")
|
|
241
|
+
add("uninstall", cmd_uninstall, "remove a robot kit (<robot>) or one old version (<robot>==X.Y.Z)").add_argument("spec")
|
|
242
|
+
add("versions", cmd_versions, "installed and available versions").add_argument("short")
|
|
243
|
+
add("cleanup", cmd_cleanup, "remove old versions and unused environments").add_argument("short", nargs="?")
|
|
244
|
+
add("doctor", cmd_doctor, "check this installation")
|
|
245
|
+
sub.add_parser("run", help="run <robot> <command> [args...]")
|
|
246
|
+
return ap
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv=None):
|
|
250
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
251
|
+
token = None
|
|
252
|
+
try:
|
|
253
|
+
if argv[:1] == ["run"]:
|
|
254
|
+
if len(argv) < 3 or argv[1] in ("-h", "--help"):
|
|
255
|
+
out("usage: zelpi-kit run <robot> <command> [args...] (arguments are passed to the kit untouched)")
|
|
256
|
+
return 0 if argv[1:2] in (["-h"], ["--help"]) else 2
|
|
257
|
+
if not store.SHORT_RE.match(argv[1]):
|
|
258
|
+
raise KitError("bad robot name %r" % argv[1])
|
|
259
|
+
return runmod.run(argv[1], argv[2], argv[3:])
|
|
260
|
+
try:
|
|
261
|
+
a = build_parser().parse_args(argv)
|
|
262
|
+
except SystemExit as e: # argparse: usage error (2) or --help (0)
|
|
263
|
+
return e.code if isinstance(e.code, int) else 2
|
|
264
|
+
if not getattr(a, "fn", None):
|
|
265
|
+
build_parser().print_help()
|
|
266
|
+
return 2
|
|
267
|
+
return a.fn(a) or 0
|
|
268
|
+
except KeyboardInterrupt:
|
|
269
|
+
sys.stderr.write("zelpi-kit: interrupted\n")
|
|
270
|
+
return 130
|
|
271
|
+
except KitError as e:
|
|
272
|
+
sys.stderr.write("zelpi-kit: error: %s\n" % redact(e, token))
|
|
273
|
+
return 1
|
|
274
|
+
except OSError as e:
|
|
275
|
+
sys.stderr.write("zelpi-kit: error: %s\n" % redact("%s: %s" % (e.strerror or e, e.filename or ""), token))
|
|
276
|
+
return 1
|
|
277
|
+
except Exception as e: # never a traceback (it could carry the token); ZELPI_KIT_DEBUG=1 prints a redacted one
|
|
278
|
+
sys.stderr.write("zelpi-kit: internal error: %s: %s\n" % (type(e).__name__, redact(e, token)))
|
|
279
|
+
if os.environ.get("ZELPI_KIT_DEBUG"):
|
|
280
|
+
import traceback
|
|
281
|
+
sys.stderr.write(redact(traceback.format_exc()) + "\n")
|
|
282
|
+
return 1
|
zelpi_kit/env.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Dependency environments (envs/<short>-<lockhash12>/), interpreter search, the smoke test."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import store
|
|
10
|
+
from .store import KitError, TOKEN_RE
|
|
11
|
+
|
|
12
|
+
MARKER = "env.ok" # written last: a folder without it is incomplete and is rebuilt
|
|
13
|
+
_PYVER = "import sys;print('%d.%d.%d' % sys.version_info[:3])"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def lock_hash(lock_bytes):
|
|
17
|
+
return hashlib.sha256(lock_bytes.replace(b"\r\n", b"\n")).hexdigest()[:12]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def env_python(env_path):
|
|
21
|
+
return os.path.join(env_path, "Scripts", "python.exe") if os.name == "nt" else os.path.join(env_path, "bin", "python")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# ---------- python ranges ----------
|
|
25
|
+
|
|
26
|
+
def _parse_ver(s):
|
|
27
|
+
m = re.fullmatch(r"(\d+)(?:\.(\d+))?(?:\.(\d+|\*))?", s.strip())
|
|
28
|
+
if not m:
|
|
29
|
+
raise KitError("cannot read the python range %r" % s)
|
|
30
|
+
return tuple(x for x in m.groups() if x is not None)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def py_ok(spec, v):
|
|
34
|
+
"""PEP 440 style subset: ==, !=, >=, <=, <, >, ~=, with 3.12.* prefixes. v = (major, minor, micro)."""
|
|
35
|
+
for item in [x for x in spec.split(",") if x.strip()]:
|
|
36
|
+
m = re.fullmatch(r"\s*(==|!=|>=|<=|<|>|~=)\s*(\S+)\s*", item)
|
|
37
|
+
if not m:
|
|
38
|
+
raise KitError("cannot read the python range %r" % spec)
|
|
39
|
+
op, parts = m.group(1), _parse_ver(m.group(2))
|
|
40
|
+
wild = parts[-1] == "*"
|
|
41
|
+
nums = tuple(int(x) for x in parts if x != "*")
|
|
42
|
+
pad = nums + (0,) * (3 - len(nums))
|
|
43
|
+
if op in ("==", "!="):
|
|
44
|
+
hit = v[:len(nums)] == nums if wild else tuple(v) == pad
|
|
45
|
+
if hit != (op == "=="):
|
|
46
|
+
return False
|
|
47
|
+
elif op == "~=":
|
|
48
|
+
if len(nums) < 2 or not (tuple(v) >= pad and v[:len(nums) - 1] == nums[:-1]):
|
|
49
|
+
return False
|
|
50
|
+
elif not {">=": tuple(v) >= pad, "<=": tuple(v) <= pad, "<": tuple(v) < pad, ">": tuple(v) > pad}[op]:
|
|
51
|
+
return False
|
|
52
|
+
return True
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _probe(exe):
|
|
56
|
+
try:
|
|
57
|
+
r = subprocess.run([exe, "-I", "-c", _PYVER], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
58
|
+
stdin=subprocess.DEVNULL, timeout=30)
|
|
59
|
+
return tuple(int(x) for x in r.stdout.decode().strip().split(".")) if r.returncode == 0 else None
|
|
60
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def find_pythons(spec):
|
|
65
|
+
"""[(version, exe)] of interpreters that satisfy spec, newest first. Never uses a bare 'python3' on Windows
|
|
66
|
+
(it can be the Microsoft Store stub)."""
|
|
67
|
+
cands = [sys.executable]
|
|
68
|
+
if os.name == "nt":
|
|
69
|
+
if shutil.which("py"):
|
|
70
|
+
try:
|
|
71
|
+
out = subprocess.run(["py", "-0p"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
72
|
+
stdin=subprocess.DEVNULL, timeout=30).stdout.decode("utf-8", "replace")
|
|
73
|
+
for line in out.splitlines():
|
|
74
|
+
m = re.match(r"\s*-(?:V:)?(\d+\.\d+)\S*\s+\*?\s*(.+?)\s*$", line)
|
|
75
|
+
if m and os.path.isfile(m.group(2)):
|
|
76
|
+
cands.append(m.group(2))
|
|
77
|
+
except (OSError, subprocess.SubprocessError):
|
|
78
|
+
pass
|
|
79
|
+
else:
|
|
80
|
+
cands += [shutil.which("python3.%d" % m) for m in range(16, 8, -1)] + [shutil.which("python3")]
|
|
81
|
+
found, done = [], set()
|
|
82
|
+
for exe in cands:
|
|
83
|
+
if not exe or os.path.normcase(os.path.realpath(exe)) in done:
|
|
84
|
+
continue
|
|
85
|
+
done.add(os.path.normcase(os.path.realpath(exe)))
|
|
86
|
+
v = _probe(exe)
|
|
87
|
+
if v and py_ok(spec, v):
|
|
88
|
+
found.append((v, exe))
|
|
89
|
+
return sorted(found, reverse=True)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _uv():
|
|
93
|
+
return None if os.environ.get("ZELPI_NO_UV") else shutil.which("uv")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def no_python_message(spec):
|
|
97
|
+
return ("no Python satisfying %r was found. Install one (python.org / your package manager) or install uv "
|
|
98
|
+
"(https://docs.astral.sh/uv/), which can fetch it, then run the command again" % spec)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------- child processes ----------
|
|
102
|
+
|
|
103
|
+
def child_env(**extra):
|
|
104
|
+
"""Environment for children: no python path leaks, no token-shaped value, caches kept inside ZELPI_HOME."""
|
|
105
|
+
e = {k: v for k, v in os.environ.items() if not TOKEN_RE.search(v) and k not in ("PYTHONPATH", "PYTHONHOME")}
|
|
106
|
+
e.update(extra)
|
|
107
|
+
return e
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _build_env():
|
|
111
|
+
h = store.home()
|
|
112
|
+
secret = re.compile(r"(KEY|TOKEN|SECRET|PASSWORD|CREDENTIALS?)$", re.I) # installers need none of the operator's keys
|
|
113
|
+
keep = {k: v for k, v in child_env().items() if not secret.search(k)}
|
|
114
|
+
return dict(keep, PIP_CACHE_DIR=os.path.join(h, "cache", "pip"), UV_CACHE_DIR=os.path.join(h, "cache", "uv"),
|
|
115
|
+
UV_PYTHON_INSTALL_DIR=os.path.join(h, "pythons"), PIP_DISABLE_PIP_VERSION_CHECK="1",
|
|
116
|
+
PIP_NO_INPUT="1")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _run(cmd, what, capture=False):
|
|
120
|
+
try:
|
|
121
|
+
r = subprocess.run(cmd, env=_build_env(), stdin=subprocess.DEVNULL,
|
|
122
|
+
stdout=subprocess.PIPE if capture else None, stderr=subprocess.STDOUT if capture else None)
|
|
123
|
+
except OSError as e:
|
|
124
|
+
raise KitError("%s failed: %s" % (what, e))
|
|
125
|
+
if r.returncode != 0:
|
|
126
|
+
tail = (r.stdout or b"").decode("utf-8", "replace")[-600:] if capture else "(output above)"
|
|
127
|
+
raise KitError("%s failed (exit %d) %s" % (what, r.returncode, store.redact(tail)))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def lock_has_deps(text):
|
|
131
|
+
return any(ln.strip() and not ln.lstrip().startswith("#") for ln in text.splitlines())
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def ensure_env(name, spec, lock_path, deps):
|
|
135
|
+
"""Reuse env `name` when its marker says complete; else (re)build it. Returns the env folder."""
|
|
136
|
+
path = store.env_dir(name)
|
|
137
|
+
marker = os.path.join(path, MARKER)
|
|
138
|
+
with open(lock_path, "r", encoding="utf-8") as f:
|
|
139
|
+
lock_text = f.read()
|
|
140
|
+
want_deps = deps and lock_has_deps(lock_text)
|
|
141
|
+
info = None
|
|
142
|
+
if os.path.exists(marker) and os.path.exists(env_python(path)):
|
|
143
|
+
try:
|
|
144
|
+
info = store.read_json(marker)
|
|
145
|
+
info["python"] = tuple(int(x) for x in info["python"].split("."))
|
|
146
|
+
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
|
147
|
+
info = None # unreadable marker = incomplete
|
|
148
|
+
if info is not None and not py_ok(spec, info["python"]):
|
|
149
|
+
raise KitError("environment %s was built with Python %s but this kit needs %s with the same dependency lock; "
|
|
150
|
+
"run 'zelpi-kit uninstall' for this robot and install again"
|
|
151
|
+
% (name, ".".join(map(str, info["python"])), spec))
|
|
152
|
+
if info is not None and (info.get("deps") or not want_deps):
|
|
153
|
+
return path
|
|
154
|
+
if info is None:
|
|
155
|
+
if os.path.isdir(path):
|
|
156
|
+
short = name.rsplit("-", 1)[0]
|
|
157
|
+
if any(store.is_running(short, v) for v in store.installed_versions(short)): # any version of this robot: the env may be its own
|
|
158
|
+
raise KitError("the environment %s is damaged and a %s agent is running: stop the agent first, then install again" % (name, short))
|
|
159
|
+
store.safe_rmtree(path) # incomplete leftovers
|
|
160
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
161
|
+
_create(path, spec, want_deps)
|
|
162
|
+
py = env_python(path)
|
|
163
|
+
ver = _probe(py)
|
|
164
|
+
if not ver or not py_ok(spec, ver):
|
|
165
|
+
raise KitError("the new environment's Python %s does not satisfy %s" % (ver, spec))
|
|
166
|
+
if want_deps:
|
|
167
|
+
_install_deps(py, lock_path, "--hash=sha256:" in lock_text)
|
|
168
|
+
store.write_json(marker, {"lock": name.split("-")[-1], "python": "%d.%d.%d" % ver, "deps": bool(want_deps)})
|
|
169
|
+
return path
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _create(path, spec, need_pip=True):
|
|
173
|
+
uv = _uv()
|
|
174
|
+
if uv:
|
|
175
|
+
try:
|
|
176
|
+
_run([uv, "venv", "--python", spec, "--no-config", path], "creating the environment with uv", capture=True)
|
|
177
|
+
return
|
|
178
|
+
except KitError as e:
|
|
179
|
+
if os.path.isdir(path):
|
|
180
|
+
store.safe_rmtree(path)
|
|
181
|
+
sys.stderr.write("zelpi-kit: uv could not build the environment (%s); trying a local Python\n" % e)
|
|
182
|
+
found = find_pythons(spec)
|
|
183
|
+
if not found:
|
|
184
|
+
raise KitError(no_python_message(spec))
|
|
185
|
+
try:
|
|
186
|
+
_run([found[0][1], "-I", "-m", "venv", path], "creating the environment", capture=True)
|
|
187
|
+
except KitError as e:
|
|
188
|
+
if need_pip:
|
|
189
|
+
raise KitError("%s -- on Debian/Ubuntu install python3-venv, or install uv" % e)
|
|
190
|
+
if os.path.isdir(path):
|
|
191
|
+
store.safe_rmtree(path)
|
|
192
|
+
# nothing to install: an environment without pip is enough (Debian has no ensurepip by default)
|
|
193
|
+
_run([found[0][1], "-I", "-m", "venv", "--without-pip", path], "creating the environment", capture=True)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _install_deps(py, lock_path, hashes):
|
|
197
|
+
uv = _uv()
|
|
198
|
+
opts = ["--only-binary", ":all:", "-r", lock_path] + (["--require-hashes"] if hashes else []) # wheels only: no build script ever runs
|
|
199
|
+
cmd = [uv, "pip", "install", "--python", py] + opts if uv else [py, "-I", "-m", "pip", "install", "--no-input"] + opts
|
|
200
|
+
_run(cmd, "installing dependencies")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def launch_cmd(py, vroot, short, argv):
|
|
204
|
+
"""By file, never `-m`: -m puts the operator's current folder first on sys.path (a stray json.py would run in the agent)."""
|
|
205
|
+
return [py, os.path.join(vroot, "zelpi_%s" % short, "__main__.py")] + list(argv)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def smoke(py, vroot, short, argv, timeout=300):
|
|
209
|
+
"""Run the kit's own smoke command (e.g. `agent --help`) in a child process; exit code 0 is required."""
|
|
210
|
+
cmd = launch_cmd(py, vroot, short, argv)
|
|
211
|
+
try:
|
|
212
|
+
r = subprocess.run(cmd, cwd=vroot, env=child_env(PYTHONDONTWRITEBYTECODE="1"),
|
|
213
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
|
|
214
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
215
|
+
raise KitError("smoke test could not run: %s" % e)
|
|
216
|
+
if r.returncode != 0:
|
|
217
|
+
raise KitError("smoke test failed (%s exit %d): %s" % (" ".join(argv), r.returncode,
|
|
218
|
+
store.redact(r.stdout.decode("utf-8", "replace")[-600:])))
|