Repository navigation
Expand file tree
/
Copy pathsmoke.py
More file actions
281 lines (242 loc) · 12.6 KB
/
Copy pathsmoke.py
File metadata and controls
281 lines (242 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
130
131
132
133
134
135
136
137
138
139
140
141
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python3
"""Loads packages into RustGIS and runs them on the World Atlas sample.
python scripts/smoke.py [--cli path/to/rustgis-cli] # the packages this build made
python scripts/smoke.py --all [--cli path/to/rustgis-cli] # every listed package (nightly)
python scripts/smoke.py --runtime wasm|process ... # only WebAssembly or process plugins
For each plugin: RustGIS must load it and list its commands; each tool runs with its defaults
(layer parameters get a sample layer of the right kind) and must succeed, unless a service that it
reads refuses the client (HTTP 401, 403 or 429, or a server error). That is reported as a skip: the
check tests the plugin, and a service can refuse a runner's address whatever the plugin sends. Each
command that needs no parameters runs too (a failure there is reported but doesn't fail the check,
since a command may need a selection or a layer the sample doesn't have).
A process plugin ("runtime": "process") runs from its unpacked files, so it is installed into a
scratch plugins folder first (`rustgis-cli plugins install`), run as installed, and uninstalled.
When the manifest declares `python`, installation also prepares its environment with uv,
downloading Python and its packages.
One with no program for Linux is skipped (RustGIS can't load it here; build.py checks its files).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DIST = ROOT / "dist"
MAX_PACKAGE = 64 * 1024 * 1024
# A sample layer for each layer kind, and a field of it.
SAMPLE = {"polygonLayer": "Countries", "pointLayer": "Cities", "vectorLayer": "Countries", "layer": "Countries"}
FIELDS = {"field": "name", "numericField": "pop_est"}
# Installing a process plugin can download Python and its packages.
INSTALL_TIMEOUT = 1800
def clean_env(plugins_dir: str, home: str) -> dict:
"""The environment RustGIS and the plugins it runs get: little of the caller's.
A process plugin is a program that isn't sandboxed, so it sees only what running needs, not
the CI job's variables.
Args:
plugins_dir: The scratch plugins folder.
home: A scratch home folder.
Returns:
The environment variables.
"""
# A proxy, if the machine needs one to reach PyPI, and uv's cache, so the nightly's runs
# share their downloads when the caller sets one.
keep = ("PATH", "LANG", "LC_ALL", "TMPDIR", "SSL_CERT_FILE", "SSL_CERT_DIR", "RUSTGIS_UV", "UV_CACHE_DIR")
keep += ("HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy")
return {**{k: os.environ[k] for k in keep if k in os.environ}, "HOME": home, "RUSTGIS_PLUGINS_DIR": plugins_dir}
def run(cli: str, package: Path, cmds: list[str], env: dict, installed: bool = False) -> subprocess.CompletedProcess:
"""Runs commands in rustgis-cli on the sample, with the plugin loaded.
Args:
cli: The rustgis-cli program.
package: The plugin's package.
cmds: The commands to run, in order.
env: The environment (`clean_env`), which names the scratch plugins folder.
installed: The plugin is installed in that folder (a process plugin): load the
installed plugins rather than the package.
Returns:
The finished process.
"""
args = [cli, "run", "--sample"] if installed else [cli, "run", "--no-plugins", "--plugin", str(package), "--sample"]
for c in cmds:
args += ["--cmd", c]
try:
return subprocess.run(args, capture_output=True, text=True, timeout=600, env=env)
except subprocess.TimeoutExpired:
# A plugin that hangs fails its own check, and the others still run.
return subprocess.CompletedProcess(args, 1, "", "it timed out after 10 minutes")
def plugins(cli: str, args: list[str], env: dict) -> subprocess.CompletedProcess:
"""Runs `rustgis-cli plugins <args>` on the scratch plugins folder.
Args:
cli: The rustgis-cli program.
args: The subcommand and its argument (`install <file>`, `uninstall <id>`).
env: The environment (`clean_env`), which names the scratch plugins folder.
Returns:
The finished process.
"""
try:
return subprocess.run([cli, "plugins", *args], capture_output=True, text=True, timeout=INSTALL_TIMEOUT, env=env)
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess(args, 1, "", f"it took more than {INSTALL_TIMEOUT // 60} minutes")
def runs_on_linux(manifest: dict) -> bool:
"""Whether a process plugin's `run` names a program for Linux (its own, or the default).
Args:
manifest: The plugin's plugin.json.
Returns:
True when it does.
"""
run = manifest.get("run")
return isinstance(run, list) or (isinstance(run, dict) and bool(run.get("linux") or run.get("default")))
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--cli", default=os.environ.get("RUSTGIS_CLI") or shutil.which("rustgis-cli") or "rustgis-cli")
ap.add_argument("--all", action="store_true", help="every listed package, downloading published ones")
ap.add_argument("--shard", default="1/1", help="with --all, run part k of n (k/n), for parallel jobs")
ap.add_argument("--runtime", choices=("all", "wasm", "process"), default="all", help="run only WebAssembly or process plugins")
args = ap.parse_args()
k, n = (int(x) for x in args.shard.split("/"))
registry = json.loads((DIST / "registry.json").read_text(encoding="utf-8"))
failures = 0
with tempfile.TemporaryDirectory() as plugins_dir, tempfile.TemporaryDirectory() as downloads, tempfile.TemporaryDirectory() as home:
env = clean_env(plugins_dir, home)
ran = 0
for i, e in enumerate(registry["plugins"]):
if i % n != k - 1:
continue
# A plugin with a package per platform is run from the one for Linux, as RustGIS
# here would download it.
if "packages" in e:
linux = e["packages"].get("linux")
if linux is None:
print(f"== {e['id']} {e['version']}: no package for Linux, not run here (run it on its platforms by hand)")
continue
e = {**e, **linux}
# Built by this run, or (with --all) downloaded from the bucket.
file_name = e["package"].rsplit("/", 1)[-1]
package = DIST / "packages" / e["id"] / file_name
if not package.is_file():
if not args.all:
continue
package = Path(downloads) / file_name
if not str(e["package"]).startswith("https://"):
print(f"error: {e['id']}: package URL isn't https: {e['package']}")
failures += 1
continue
try:
req = urllib.request.Request(e["package"], headers={"User-Agent": "rustgis-plugins-smoke"})
with urllib.request.urlopen(req, timeout=120) as r: # noqa: S310 - https only, checked above
data = r.read(MAX_PACKAGE + 1)
except Exception as err: # noqa: BLE001 - one bad download mustn't stop the run
print(f"error: {e['id']}: can't download {e['package']}: {err}")
failures += 1
continue
# Test what users install: the bytes the registry lists.
if len(data) > MAX_PACKAGE or hashlib.sha256(data).hexdigest() != e.get("sha256"):
print(f"error: {e['id']}: {e['package']} doesn't match the registry's SHA-256")
failures += 1
continue
package.write_bytes(data)
with zipfile.ZipFile(package) as z:
root = "" if "plugin.json" in z.namelist() else next(n[: -len("plugin.json")] for n in z.namelist() if n.endswith("/plugin.json"))
manifest = json.loads(z.read(root + "plugin.json"))
process = manifest.get("runtime") == "process"
if args.runtime != "all" and process != (args.runtime == "process"):
print(f"== {e['id']} {e['version']}: a {'process' if process else 'WebAssembly'} plugin, not run here")
continue
print(f"== {e['id']} {e['version']}")
if process and not runs_on_linux(manifest):
# RustGIS won't load it here at all; build.py checked its manifest and files.
print(" skipped: a process plugin with no program for Linux, which RustGIS can't run here (run it on its platforms by hand)")
continue
ran += 1
try:
# A process plugin runs from its unpacked files: installed (with its Python
# environment) here, and removed after, even when the install half worked.
if process and (got := plugins(args.cli, ["install", str(package)], env)).returncode != 0:
print(f"error: RustGIS couldn't install it:\n{got.stderr}")
failures += 1
continue
failures += exercise(args.cli, package, e["id"], manifest, env, process)
finally:
if process:
plugins(args.cli, ["uninstall", e["id"]], env)
if ran == 0:
print("no new packages to run" if not args.all else "no packages in this shard")
print(f"{ran} plugins run, {failures} failures")
return 1 if failures else 0
# A service that answers one of these refused the client itself: no credentials, its own policy
# against this address, a rate limit or a broken server. The request may be exactly right.
REFUSED = (401, 403, 429)
STATUS = re.compile(r"HTTP (\d{3}) from https?://")
def refused_status(stderr: str) -> str | None:
"""The HTTP status a service answered when it refused the client, not the request.
Args:
stderr: What the tool run wrote to its error stream.
Returns:
The status as text, or None when the run failed for any other reason.
"""
for match in STATUS.finditer(stderr):
code = int(match.group(1))
if code in REFUSED or 500 <= code < 600:
return str(code)
return None
def exercise(cli: str, package: Path, pid: str, manifest: dict, env: dict, installed: bool) -> int:
"""Loads a plugin in rustgis-cli and runs its commands and tools on the sample.
Args:
cli: The rustgis-cli program.
package: The plugin's package.
pid: The plugin's id.
manifest: Its plugin.json.
env: The environment (`clean_env`), which names the scratch plugins folder.
installed: It is installed there (a process plugin) rather than loaded from the package.
Returns:
The number of failures.
"""
failures = 0
listed = run(cli, package, ["info.commands"], env, installed)
if listed.returncode != 0:
print(f"error: RustGIS couldn't load it:\n{listed.stderr}")
return 1
ids = {c["id"] for c in json.loads(listed.stdout)}
for c in manifest.get("commands", []):
cid = f"plugin:{pid}/{c['id']}"
if cid not in ids:
print(f"error: {cid} isn't listed")
failures += 1
continue
if c.get("params", "{}") not in ("{}", "") and ":" in c.get("params", "") and "?" not in c.get("params", ""):
continue
r = run(cli, package, [cid], env, installed)
print(f" command {c['id']}: {'ok' if r.returncode == 0 else 'failed (allowed): ' + r.stderr.strip()}")
for t in manifest.get("tools", []):
params, skip = {}, False
for p in t.get("params", []):
if p["kind"] in SAMPLE:
params[p["name"]] = SAMPLE[p["kind"]]
elif p["kind"] in FIELDS:
params[p["name"]] = FIELDS[p["kind"]]
elif p.get("required") and "default" not in p:
skip = True
if skip:
print(f" tool {t['id']}: skipped (a required parameter has no default)")
continue
cmd = "gp.run=" + json.dumps({"tool": f"plugin:{pid}/{t['id']}", "params": params})
r = run(cli, package, [cmd], env, installed)
if r.returncode == 0:
print(f" tool {t['id']}: ok")
continue
refused = refused_status(r.stderr)
if refused:
print(f" tool {t['id']}: skipped (the service answered HTTP {refused})")
else:
print(f"error: tool {t['id']} failed: {r.stderr.strip()}")
failures += 1
return failures
if __name__ == "__main__":
sys.exit(main())