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/install.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""install / update / rollback / uninstall / cleanup. Order of an install: download, unpack, env, smoke, rename,
|
|
2
|
+
pointer. Everything before the pointer write is invisible to `run`: a failure at any step leaves the current
|
|
3
|
+
version exactly as it was."""
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from . import env, net, store, wheel
|
|
9
|
+
from .store import KitError, VER_RE, vt
|
|
10
|
+
|
|
11
|
+
_SHA_RE = re.compile(r"^[0-9a-f]{64}$")
|
|
12
|
+
_MAX_FILE = 4 << 30
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _checkpoint(step):
|
|
16
|
+
"""Tests patch this to inject a failure at a step; it does nothing in production."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def log(msg):
|
|
20
|
+
print(msg, flush=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ---------- the catalogue ----------
|
|
24
|
+
|
|
25
|
+
def fetch_catalogue(site, token):
|
|
26
|
+
cat = net.get_json(site, token, "/v1/kits")
|
|
27
|
+
if not isinstance(cat, dict) or not isinstance(cat.get("kits"), list):
|
|
28
|
+
raise KitError("the site's /v1/kits answer is not a kit list")
|
|
29
|
+
store.save_catalogue(cat)
|
|
30
|
+
return cat
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def clean_kit(raw):
|
|
34
|
+
"""Validate one catalogue entry; returns None for entries that are unusable (their names become paths)."""
|
|
35
|
+
try:
|
|
36
|
+
short = raw["short"]
|
|
37
|
+
if not (isinstance(short, str) and store.SHORT_RE.match(short) and raw["project"] == "zelpi-" + short
|
|
38
|
+
and isinstance(raw["kind"], str) and re.match(r"^[a-z0-9_]{1,32}$", raw["kind"])):
|
|
39
|
+
return None
|
|
40
|
+
versions = {}
|
|
41
|
+
for v in raw.get("versions") or []:
|
|
42
|
+
if (isinstance(v.get("version"), str) and VER_RE.match(v["version"])
|
|
43
|
+
and v.get("filename") == "zelpi_%s-%s-py3-none-any.whl" % (short, v["version"])
|
|
44
|
+
and isinstance(v.get("sha256"), str) and _SHA_RE.match(v["sha256"].lower())
|
|
45
|
+
and isinstance(v.get("size"), int) and 0 < v["size"] <= _MAX_FILE):
|
|
46
|
+
versions[v["version"]] = v
|
|
47
|
+
good = lambda x: isinstance(x, str) and VER_RE.match(x) # noqa: E731
|
|
48
|
+
return {"short": short, "project": raw["project"], "kind": raw["kind"], "versions": versions,
|
|
49
|
+
"latest": raw.get("latest") if good(raw.get("latest")) else None,
|
|
50
|
+
"min_version": raw.get("min_version") if good(raw.get("min_version")) else "0.0.0",
|
|
51
|
+
"deny": [d for d in (raw.get("deny") or []) if good(d)]}
|
|
52
|
+
except (KeyError, TypeError, AttributeError):
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def find_kit(cat, short):
|
|
57
|
+
for raw in cat["kits"]:
|
|
58
|
+
k = clean_kit(raw) if isinstance(raw, dict) else None
|
|
59
|
+
if k and k["short"] == short:
|
|
60
|
+
return k
|
|
61
|
+
raise KitError("no robot kit %r is available to your account (see 'zelpi-kit list')" % short)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def unusable(kit, version):
|
|
65
|
+
"""Why the server would refuse this version, or None."""
|
|
66
|
+
v = kit["versions"].get(version)
|
|
67
|
+
if v is not None and v.get("yanked"):
|
|
68
|
+
return "yanked"
|
|
69
|
+
if version in kit["deny"]:
|
|
70
|
+
return "denied"
|
|
71
|
+
if vt(version) < vt(kit["min_version"]):
|
|
72
|
+
return "below the minimum version %s" % kit["min_version"]
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def candidates(kit):
|
|
77
|
+
"""Usable versions up to `latest`: versions above it are staged / per-company builds, never picked automatically
|
|
78
|
+
(so yanking latest falls back to the next one below, not to something newer)."""
|
|
79
|
+
if not kit["latest"]:
|
|
80
|
+
return [] # nothing has been released yet
|
|
81
|
+
top = vt(kit["latest"])
|
|
82
|
+
return sorted((v for v in kit["versions"] if unusable(kit, v) is None and vt(v) <= top), key=vt)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def target_version(kit):
|
|
86
|
+
c = candidates(kit)
|
|
87
|
+
if not c:
|
|
88
|
+
raise KitError("%s has no installable version right now" % kit["short"])
|
|
89
|
+
return c[-1]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------- install ----------
|
|
93
|
+
|
|
94
|
+
def _sweep_tmp(short):
|
|
95
|
+
kd = store.kit_dir(short)
|
|
96
|
+
try:
|
|
97
|
+
for n in os.listdir(kd):
|
|
98
|
+
if n.startswith(".tmp-"):
|
|
99
|
+
store.safe_rmtree(os.path.join(kd, n))
|
|
100
|
+
except OSError:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _rename(src, dst):
|
|
105
|
+
for i in range(6): # Windows: antivirus may hold the fresh folder for a moment
|
|
106
|
+
try:
|
|
107
|
+
os.rename(src, dst)
|
|
108
|
+
return
|
|
109
|
+
except PermissionError:
|
|
110
|
+
if i == 5 or os.name != "nt":
|
|
111
|
+
raise
|
|
112
|
+
time.sleep(0.5)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def env_name(short, vroot):
|
|
116
|
+
with open(os.path.join(vroot, "zelpi_%s" % short, "requirements.lock"), "rb") as f:
|
|
117
|
+
return "%s-%s" % (short, env.lock_hash(f.read()))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def install_lock(short):
|
|
121
|
+
store.ensure_home()
|
|
122
|
+
lk = store.Lock(store.lock_path("install", short), True)
|
|
123
|
+
if not lk.acquire():
|
|
124
|
+
raise KitError("another zelpi-kit is installing %s right now: wait for it to finish" % short)
|
|
125
|
+
return lk
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def refuse_while_running():
|
|
129
|
+
"""Installing loads the disk, CPU and network: never beside an agent that may be holding or moving an arm."""
|
|
130
|
+
run = store.running_agents()
|
|
131
|
+
if run:
|
|
132
|
+
raise KitError("an agent is running (%s): stop it first. Nothing was changed" % ", ".join(run))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _sha_path(short, version):
|
|
136
|
+
return os.path.join(store.kit_dir(short), version + ".sha256")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _same_bytes(short, version, entry):
|
|
140
|
+
try:
|
|
141
|
+
with open(_sha_path(short, version), "r", encoding="ascii") as f:
|
|
142
|
+
return f.read().strip() == entry["sha256"].lower()
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def install(site, token, short, version=None, deps=True):
|
|
148
|
+
"""Returns (version, kit_json). Raises KitError; the current version is untouched on any failure."""
|
|
149
|
+
cat = fetch_catalogue(site, token)
|
|
150
|
+
kit = find_kit(cat, short)
|
|
151
|
+
if version is None:
|
|
152
|
+
version = target_version(kit)
|
|
153
|
+
elif version not in kit["versions"]:
|
|
154
|
+
raise KitError("%s %s is not in the catalogue (see 'zelpi-kit versions %s')" % (short, version, short))
|
|
155
|
+
elif unusable(kit, version):
|
|
156
|
+
raise KitError("%s %s is %s: refused" % (short, version, unusable(kit, version)))
|
|
157
|
+
entry = kit["versions"][version]
|
|
158
|
+
spec = entry.get("requires_python") if isinstance(entry.get("requires_python"), str) else None
|
|
159
|
+
if spec and not env._uv() and not env.find_pythons(spec):
|
|
160
|
+
raise KitError(env.no_python_message(spec))
|
|
161
|
+
refuse_while_running()
|
|
162
|
+
with install_lock(short):
|
|
163
|
+
_sweep_tmp(short)
|
|
164
|
+
vdir = store.version_dir(short, version)
|
|
165
|
+
tmp = os.path.join(store.kit_dir(short), ".tmp-%d-%d" % (os.getpid(), int(time.monotonic() * 1000)))
|
|
166
|
+
reuse = os.path.isdir(vdir) and _same_bytes(short, version, entry) and _intact(vdir, short, version)
|
|
167
|
+
try:
|
|
168
|
+
if reuse:
|
|
169
|
+
root, kj = vdir, wheel.read_kit(vdir, short, kit, entry)
|
|
170
|
+
else:
|
|
171
|
+
os.makedirs(tmp)
|
|
172
|
+
whl = os.path.join(tmp, entry["filename"])
|
|
173
|
+
_checkpoint("download")
|
|
174
|
+
net.download(site, token, "/v1/pypi/files/" + entry["filename"], whl, entry["size"], entry["sha256"])
|
|
175
|
+
_checkpoint("unpack")
|
|
176
|
+
root = wheel.unpack(whl, os.path.join(tmp, "unpacked"), short, version)
|
|
177
|
+
os.unlink(whl)
|
|
178
|
+
wheel.verify_record(root, short, version)
|
|
179
|
+
kj = wheel.read_kit(root, short, kit, entry)
|
|
180
|
+
_checkpoint("env")
|
|
181
|
+
name = env_name(short, root)
|
|
182
|
+
lock = os.path.join(root, "zelpi_%s" % short, "requirements.lock")
|
|
183
|
+
envp = env.ensure_env(name, kj["python"], lock, deps)
|
|
184
|
+
_checkpoint("smoke")
|
|
185
|
+
env.smoke(env.env_python(envp), root, short, kj["smoke"])
|
|
186
|
+
_checkpoint("rename")
|
|
187
|
+
if not reuse:
|
|
188
|
+
old = os.path.join(tmp, "replaced")
|
|
189
|
+
if os.path.isdir(vdir): # damaged, or other bytes under the same number: swapped only now that the new one is verified
|
|
190
|
+
_rename(vdir, old)
|
|
191
|
+
try:
|
|
192
|
+
_rename(root, vdir)
|
|
193
|
+
except OSError:
|
|
194
|
+
if os.path.isdir(old):
|
|
195
|
+
_rename(old, vdir)
|
|
196
|
+
raise
|
|
197
|
+
with open(_sha_path(short, version), "w", encoding="ascii") as f:
|
|
198
|
+
f.write(entry["sha256"].lower())
|
|
199
|
+
_checkpoint("pointer")
|
|
200
|
+
cur = store.read_current_safe(short)
|
|
201
|
+
prev = cur["version"] if cur and cur["version"] != version else (cur or {}).get("previous")
|
|
202
|
+
store.write_json(os.path.join(store.kit_dir(short), "current.json"),
|
|
203
|
+
{"version": version, "previous": prev, "env": name}, mode=0o644)
|
|
204
|
+
_prune(short)
|
|
205
|
+
finally:
|
|
206
|
+
if os.path.isdir(tmp):
|
|
207
|
+
store.safe_rmtree(tmp)
|
|
208
|
+
return version, kj
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _intact(vdir, short, version):
|
|
212
|
+
try:
|
|
213
|
+
wheel.verify_record(vdir, short, version, strict=False)
|
|
214
|
+
return True
|
|
215
|
+
except (KitError, OSError):
|
|
216
|
+
return False
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def notice_recheck(kj, short, version):
|
|
220
|
+
if kj.get("recheck"):
|
|
221
|
+
log("NOTICE: %s %s asks you to REPEAT the hardware ladder (read-only checks, then supervised "
|
|
222
|
+
"point-to-point) before any motion: it changed something the earlier evidence does not cover." % (short, version))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ---------- update / rollback ----------
|
|
226
|
+
|
|
227
|
+
def update(site, token, short):
|
|
228
|
+
"""Latest only, never a downgrade, skips yanked / denied. Returns the new version or None."""
|
|
229
|
+
cur = store.read_current_safe(short)
|
|
230
|
+
if not cur:
|
|
231
|
+
raise KitError("%s is not installed: run 'zelpi-kit install %s'" % (short, short))
|
|
232
|
+
cat = fetch_catalogue(site, token)
|
|
233
|
+
kit = find_kit(cat, short)
|
|
234
|
+
why = unusable(kit, cur["version"])
|
|
235
|
+
if why:
|
|
236
|
+
log("WARNING: the installed %s %s is %s on the server: it will be refused by the site." % (short, cur["version"], why))
|
|
237
|
+
c = candidates(kit)
|
|
238
|
+
best = c[-1] if c else None
|
|
239
|
+
if best is None or vt(best) <= vt(cur["version"]):
|
|
240
|
+
if why:
|
|
241
|
+
raise KitError("there is no newer usable version of %s. %s" % (short, "Run 'zelpi-kit rollback %s' to go back to %s" % (short, cur["previous"])
|
|
242
|
+
if cur.get("previous") and unusable(kit, cur["previous"]) is None else
|
|
243
|
+
"Run 'zelpi-kit install %s==%s'" % (short, best) if best else "Wait for the next release"))
|
|
244
|
+
log("%s %s is up to date" % (short, cur["version"]))
|
|
245
|
+
return None
|
|
246
|
+
v, kj = install(site, token, short, best)
|
|
247
|
+
log("updated %s %s -> %s (rollback with: zelpi-kit rollback %s)" % (short, cur["version"], v, short))
|
|
248
|
+
notice_recheck(kj, short, v)
|
|
249
|
+
return v
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def rollback(short):
|
|
253
|
+
with install_lock(short):
|
|
254
|
+
cur = store.read_current_safe(short)
|
|
255
|
+
if not cur or not cur.get("previous"):
|
|
256
|
+
raise KitError("%s has no previous version to roll back to" % short)
|
|
257
|
+
prev = cur["previous"]
|
|
258
|
+
vdir = store.version_dir(short, prev)
|
|
259
|
+
if not os.path.isdir(vdir) or not _intact(vdir, short, prev):
|
|
260
|
+
raise KitError("previous version %s is missing or damaged: run 'zelpi-kit install %s==%s'" % (prev, short, prev))
|
|
261
|
+
name = env_name(short, vdir)
|
|
262
|
+
if not os.path.exists(os.path.join(store.env_dir(name), env.MARKER)):
|
|
263
|
+
raise KitError("the environment of %s is incomplete: run 'zelpi-kit install %s==%s'" % (prev, short, prev))
|
|
264
|
+
store.write_json(os.path.join(store.kit_dir(short), "current.json"),
|
|
265
|
+
{"version": prev, "previous": cur["version"], "env": name}, mode=0o644)
|
|
266
|
+
log("rolled %s back: %s -> %s" % (short, cur["version"], prev))
|
|
267
|
+
return prev
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# ---------- cleanup / uninstall ----------
|
|
271
|
+
|
|
272
|
+
def _try_remove_version(short, version):
|
|
273
|
+
"""Remove one version folder unless an agent runs from it (exclusive probe, held while deleting)."""
|
|
274
|
+
lk = store.Lock(store.lock_path("run", short, version), True)
|
|
275
|
+
try:
|
|
276
|
+
if not lk.acquire():
|
|
277
|
+
return False
|
|
278
|
+
store.safe_rmtree(store.version_dir(short, version))
|
|
279
|
+
return True
|
|
280
|
+
except OSError:
|
|
281
|
+
return False
|
|
282
|
+
finally:
|
|
283
|
+
lk.release()
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cleanup(short):
|
|
287
|
+
refuse_while_running()
|
|
288
|
+
with install_lock(short): # never prune while another install is between rename and pointer
|
|
289
|
+
_prune(short)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _prune(short):
|
|
293
|
+
"""Keep current + previous (and every version still running) and the envs those use; remove the rest."""
|
|
294
|
+
cur = store.read_current_safe(short)
|
|
295
|
+
if not cur:
|
|
296
|
+
return
|
|
297
|
+
keep = {cur["version"], cur.get("previous")}
|
|
298
|
+
for v in store.installed_versions(short):
|
|
299
|
+
if v not in keep:
|
|
300
|
+
_try_remove_version(short, v)
|
|
301
|
+
used = set()
|
|
302
|
+
for v in store.installed_versions(short):
|
|
303
|
+
try:
|
|
304
|
+
used.add(env_name(short, store.version_dir(short, v)))
|
|
305
|
+
except OSError:
|
|
306
|
+
pass
|
|
307
|
+
used.add(cur["env"])
|
|
308
|
+
try:
|
|
309
|
+
names = os.listdir(store.p("envs"))
|
|
310
|
+
except OSError:
|
|
311
|
+
names = []
|
|
312
|
+
for n in names:
|
|
313
|
+
if n.startswith(short + "-") and store.ENV_RE.match(n) and n not in used:
|
|
314
|
+
try:
|
|
315
|
+
store.safe_rmtree(store.env_dir(n))
|
|
316
|
+
except OSError:
|
|
317
|
+
pass
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def uninstall(short, version=None):
|
|
321
|
+
"""A whole robot kit (all versions, its envs), or one version that is neither current nor previous."""
|
|
322
|
+
with install_lock(short):
|
|
323
|
+
cur = store.read_current_safe(short)
|
|
324
|
+
versions = store.installed_versions(short)
|
|
325
|
+
if version:
|
|
326
|
+
if version not in versions:
|
|
327
|
+
raise KitError("%s %s is not installed" % (short, version))
|
|
328
|
+
if cur and version in (cur["version"], cur.get("previous")):
|
|
329
|
+
raise KitError("%s is the current or previous version: refused (use rollback, or uninstall %s)" % (version, short))
|
|
330
|
+
if not _try_remove_version(short, version):
|
|
331
|
+
raise KitError("%s %s is running: stop the agent first" % (short, version))
|
|
332
|
+
return
|
|
333
|
+
if not versions and not os.path.isdir(store.kit_dir(short)):
|
|
334
|
+
raise KitError("%s is not installed" % short)
|
|
335
|
+
held = []
|
|
336
|
+
try:
|
|
337
|
+
for v in versions: # hold every run lock exclusive so no agent can start while we delete
|
|
338
|
+
lk = store.Lock(store.lock_path("run", short, v), True)
|
|
339
|
+
if not lk.acquire():
|
|
340
|
+
raise KitError("%s %s is running: stop the agent first" % (short, v))
|
|
341
|
+
held.append(lk)
|
|
342
|
+
for v in versions:
|
|
343
|
+
store.safe_rmtree(store.version_dir(short, v))
|
|
344
|
+
for n in os.listdir(store.p("envs")) if os.path.isdir(store.p("envs")) else []:
|
|
345
|
+
if n.startswith(short + "-"):
|
|
346
|
+
store.safe_rmtree(store.env_dir(n))
|
|
347
|
+
store.safe_rmtree(store.kit_dir(short)) # current.json, leftovers
|
|
348
|
+
finally:
|
|
349
|
+
for lk in held:
|
|
350
|
+
lk.release()
|
zelpi_kit/net.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""HTTP with redirects handled by hand: the token goes to the site's own origin and nowhere else."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import urllib.parse as up
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .store import KitError, redact
|
|
11
|
+
|
|
12
|
+
TIMEOUT = 30 # seconds per socket operation
|
|
13
|
+
MAX_REDIRECTS = 5
|
|
14
|
+
JSON_MAX = 16 << 20
|
|
15
|
+
DEADLINE = 1800 # ponytail: wall limit for one download; a rate-based limit if slow links matter
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NetError(KitError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Unreachable(NetError):
|
|
23
|
+
"""The server could not be reached at all (offline, DNS, refused, timeout)."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def origin(url):
|
|
27
|
+
s = up.urlsplit(url)
|
|
28
|
+
port = s.port or (443 if s.scheme == "https" else 80)
|
|
29
|
+
return (s.scheme, (s.hostname or "").lower(), port)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def check_site(site):
|
|
33
|
+
"""https only; plain http only for localhost / 127.0.0.1 / ::1 (tests, tunnels)."""
|
|
34
|
+
s = up.urlsplit(site)
|
|
35
|
+
if s.scheme == "https" and s.hostname and not s.username:
|
|
36
|
+
return
|
|
37
|
+
if s.scheme == "http" and s.hostname in ("localhost", "127.0.0.1", "::1") and not s.username:
|
|
38
|
+
return
|
|
39
|
+
raise KitError("refusing site %r: it must be https (plain http is only allowed for localhost)" % site)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def next_hop(cur, location):
|
|
43
|
+
"""The URL a redirect points to, or an error when following it would be unsafe."""
|
|
44
|
+
new = up.urljoin(cur, location)
|
|
45
|
+
s = up.urlsplit(new)
|
|
46
|
+
if s.scheme not in ("http", "https") or not s.hostname:
|
|
47
|
+
raise NetError("refused redirect to %r" % redact(new))
|
|
48
|
+
if s.username or s.password:
|
|
49
|
+
raise NetError("refused redirect with credentials in the URL")
|
|
50
|
+
if up.urlsplit(cur).scheme == "https" and s.scheme == "http":
|
|
51
|
+
raise NetError("refused redirect from https to http (%s)" % s.hostname)
|
|
52
|
+
return new
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def open_url(url, site, token=None, method="GET", body=None, follow=True, timeout=None):
|
|
56
|
+
"""Returns (conn, resp) of the final response; the caller reads and closes. Authorization only to `site`'s origin."""
|
|
57
|
+
seen = set()
|
|
58
|
+
for _ in range(MAX_REDIRECTS + 1):
|
|
59
|
+
if url in seen:
|
|
60
|
+
raise NetError("redirect loop")
|
|
61
|
+
seen.add(url)
|
|
62
|
+
s = up.urlsplit(url)
|
|
63
|
+
if s.scheme not in ("http", "https") or not s.hostname:
|
|
64
|
+
raise NetError("bad URL %r" % redact(url))
|
|
65
|
+
cls = http.client.HTTPSConnection if s.scheme == "https" else http.client.HTTPConnection
|
|
66
|
+
conn = cls(s.hostname, s.port, timeout=timeout or TIMEOUT)
|
|
67
|
+
headers = {"User-Agent": "zelpi-kit/" + __version__, "Accept-Encoding": "identity"}
|
|
68
|
+
if token and origin(url) == origin(site):
|
|
69
|
+
headers["Authorization"] = "Bearer " + token
|
|
70
|
+
try:
|
|
71
|
+
conn.request(method, (s.path or "/") + ("?" + s.query if s.query else ""), body, headers)
|
|
72
|
+
resp = conn.getresponse()
|
|
73
|
+
except (OSError, http.client.HTTPException) as e:
|
|
74
|
+
conn.close()
|
|
75
|
+
raise Unreachable("cannot reach %s: %s" % (s.hostname, redact(e, token)))
|
|
76
|
+
if follow and resp.status in (301, 302, 303, 307, 308):
|
|
77
|
+
loc = resp.getheader("Location")
|
|
78
|
+
conn.close()
|
|
79
|
+
if not loc:
|
|
80
|
+
raise NetError("redirect without a Location")
|
|
81
|
+
url = next_hop(url, loc)
|
|
82
|
+
continue
|
|
83
|
+
return conn, resp
|
|
84
|
+
raise NetError("too many redirects")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _status_error(status, what):
|
|
88
|
+
if status == 401:
|
|
89
|
+
return NetError("the site rejected the download token: run 'zelpi-kit login' (create a token on the Keys page)")
|
|
90
|
+
if status == 404:
|
|
91
|
+
return NetError("%s not found (or not available to your account)" % what)
|
|
92
|
+
if status >= 500:
|
|
93
|
+
return NetError("the site had an error (HTTP %d) for %s: try again later" % (status, what))
|
|
94
|
+
return NetError("unexpected HTTP %d for %s" % (status, what))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_json(site, token, path, method="GET"):
|
|
98
|
+
conn, resp = open_url(site.rstrip("/") + path, site, token, method=method, follow=method == "GET")
|
|
99
|
+
try:
|
|
100
|
+
if resp.status != 200:
|
|
101
|
+
raise _status_error(resp.status, path)
|
|
102
|
+
data = resp.read(JSON_MAX + 1)
|
|
103
|
+
if len(data) > JSON_MAX:
|
|
104
|
+
raise NetError("answer for %s is too large" % path)
|
|
105
|
+
try:
|
|
106
|
+
return json.loads(data.decode("utf-8"))
|
|
107
|
+
except ValueError:
|
|
108
|
+
raise NetError("answer for %s is not JSON" % path)
|
|
109
|
+
except (OSError, http.client.HTTPException) as e:
|
|
110
|
+
raise Unreachable("connection lost: %s" % redact(e, token))
|
|
111
|
+
finally:
|
|
112
|
+
conn.close()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _read(resp, token):
|
|
116
|
+
try:
|
|
117
|
+
return resp.read(1 << 16)
|
|
118
|
+
except (OSError, http.client.HTTPException) as e: # timeout, reset, IncompleteRead
|
|
119
|
+
raise Unreachable("download interrupted: %s" % redact(e, token))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def download(site, token, path, dest, size, sha256):
|
|
123
|
+
"""Stream to `dest`; the size from the catalogue is a hard cap, sha256 is checked before anyone unpacks."""
|
|
124
|
+
conn, resp = open_url(site.rstrip("/") + path, site, token)
|
|
125
|
+
h, total, end = hashlib.sha256(), 0, time.monotonic() + DEADLINE
|
|
126
|
+
try:
|
|
127
|
+
if resp.status != 200:
|
|
128
|
+
raise _status_error(resp.status, path)
|
|
129
|
+
cl = resp.getheader("Content-Length")
|
|
130
|
+
if cl is not None and cl.isdigit() and int(cl) != size:
|
|
131
|
+
raise NetError("the file is %s bytes but the catalogue says %d: refused" % (cl, size))
|
|
132
|
+
with open(dest, "wb") as f:
|
|
133
|
+
while True:
|
|
134
|
+
chunk = _read(resp, token)
|
|
135
|
+
if not chunk:
|
|
136
|
+
break
|
|
137
|
+
total += len(chunk)
|
|
138
|
+
if total > size:
|
|
139
|
+
raise NetError("the download is larger than the catalogue size %d: refused" % size)
|
|
140
|
+
if time.monotonic() > end:
|
|
141
|
+
raise NetError("the download took too long")
|
|
142
|
+
h.update(chunk)
|
|
143
|
+
f.write(chunk)
|
|
144
|
+
f.flush()
|
|
145
|
+
os.fsync(f.fileno())
|
|
146
|
+
finally:
|
|
147
|
+
conn.close()
|
|
148
|
+
if total != size:
|
|
149
|
+
raise NetError("the download is truncated (%d of %d bytes)" % (total, size))
|
|
150
|
+
if h.hexdigest() != sha256.lower():
|
|
151
|
+
raise NetError("sha256 mismatch: the file is not the one the catalogue lists. Nothing was installed")
|
zelpi_kit/run.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""`run <short> <command> [args...]`: hand the terminal to the kit's agent. No pipes, no wrapper, args untouched."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import signal
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import env, store
|
|
9
|
+
from .store import KitError, vt
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def run(short, command, args):
|
|
13
|
+
cur = store.read_current(short)
|
|
14
|
+
if not cur:
|
|
15
|
+
raise KitError("%s is not installed: run 'zelpi-kit install %s'" % (short, short))
|
|
16
|
+
version = cur["version"]
|
|
17
|
+
vroot, envp = store.version_dir(short, version), store.env_dir(cur["env"])
|
|
18
|
+
py = env.env_python(envp)
|
|
19
|
+
if not (os.path.isdir(vroot) and os.path.exists(os.path.join(envp, env.MARKER)) and os.path.exists(py)):
|
|
20
|
+
raise KitError("%s %s or its environment is missing or incomplete: run 'zelpi-kit doctor', then "
|
|
21
|
+
"'zelpi-kit install %s==%s'" % (short, version, short, version))
|
|
22
|
+
try:
|
|
23
|
+
with open(os.path.join(vroot, "zelpi_%s" % short, "commands.json"), "r", encoding="utf-8") as f:
|
|
24
|
+
cmds = json.load(f)
|
|
25
|
+
except (OSError, ValueError):
|
|
26
|
+
raise KitError("%s %s has no readable commands.json: run 'zelpi-kit doctor'" % (short, version))
|
|
27
|
+
if command not in cmds:
|
|
28
|
+
raise KitError("%s has no command %r; available: %s" % (short, command, ", ".join(sorted(cmds))))
|
|
29
|
+
k = store.cached_kit(short) # last catalogue seen; run never touches the network. The SERVER decides.
|
|
30
|
+
if k and (version in (k.get("deny") or []) or (k.get("min_version") and vt(version) < vt(k["min_version"]))):
|
|
31
|
+
sys.stderr.write("WARNING: %s %s is denied or below the minimum version on the site (as of the last check): the "
|
|
32
|
+
"site will refuse it. Run 'zelpi-kit update %s' or 'zelpi-kit rollback %s'.\n"
|
|
33
|
+
% (short, version, short, short))
|
|
34
|
+
|
|
35
|
+
lock = store.Lock(store.lock_path("run", short, version), False) # shared: held for the life of the agent
|
|
36
|
+
try:
|
|
37
|
+
got = lock.acquire()
|
|
38
|
+
except OSError as e:
|
|
39
|
+
got = None
|
|
40
|
+
sys.stderr.write("WARNING: cannot create the run lock (%s); starting without it.\n" % (e.strerror or e))
|
|
41
|
+
if got is False:
|
|
42
|
+
raise KitError("%s %s is being removed: try again" % (short, version))
|
|
43
|
+
if not os.path.isdir(vroot):
|
|
44
|
+
raise KitError("%s %s was removed while starting: run 'zelpi-kit install %s'" % (short, version, short))
|
|
45
|
+
|
|
46
|
+
cmd = env.launch_cmd(py, vroot, short, [command] + list(args))
|
|
47
|
+
environ = env.child_env()
|
|
48
|
+
sys.stdout.flush()
|
|
49
|
+
sys.stderr.flush()
|
|
50
|
+
if lock.held:
|
|
51
|
+
lock.make_inheritable()
|
|
52
|
+
if os.name != "nt":
|
|
53
|
+
os.execve(py, cmd, environ) # same PID, same terminal and signals; the fd (and its flock) survives
|
|
54
|
+
# Windows: the agent is a child with our console handles. Ctrl+C / Ctrl+Break reach it (it is in our console
|
|
55
|
+
# group, which is how the operator stops it); we ignore them so we never die first and leave it unattended.
|
|
56
|
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
57
|
+
signal.signal(signal.SIGBREAK, signal.SIG_IGN)
|
|
58
|
+
child = subprocess.Popen(cmd, env=environ, close_fds=False) # inherits the lock handle: it is held while the agent lives
|
|
59
|
+
return child.wait()
|