vamp-mcp 0.1.8 → 0.2.0
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.
- package/README.md +23 -9
- package/bin/vamp-mcp.mjs +1 -1
- package/package.json +1 -1
- package/runtime/backends/kvm/debian-preseed.cfg +35 -0
- package/runtime/backends/remote_ssh/server.mjs +279 -8
- package/runtime/backends/virtualbox/provision.py +69 -21
- package/runtime/backends/virtualbox/server.mjs +390 -50
- package/runtime/guest_setup/http/postdeb.sh +47 -0
- package/runtime/guest_setup/http/postwin.ps1 +28 -0
- package/runtime/guest_setup/http/setup-all.ps1 +25 -0
- package/runtime/guest_setup/http/setup-win.cmd +7 -0
- package/runtime/guest_setup/http/setup.ps1 +29 -0
- package/runtime/guest_setup/http/setup.sh +50 -0
- package/runtime/guest_setup/kvm/setup-debian.sh +73 -0
- package/runtime/guest_setup/kvm/setup-windows.ps1 +52 -0
- package/runtime/guest_setup/recorder/README.txt +4 -0
- package/runtime/guest_setup/recorder/recorder.zip +0 -0
- package/runtime/guest_setup/recorder/setup-user.py +19 -1
- package/runtime/guest_setup/recorder/setup-win.cmd +55 -6
- package/runtime/guest_setup/recorder/setup.ps1 +57 -6
- package/runtime/guest_setup/recorder/setup.sh +18 -1
- package/runtime/guest_setup/requirements.txt +2 -0
- package/runtime/guest_setup/setup-all.ps1 +35 -0
- package/runtime/guest_setup/setup-all.sh +22 -0
- package/runtime/guest_setup/vault/Install-VCRuntime.ps1 +26 -0
- package/runtime/guest_setup/vault/setup-guest-vault.ps1 +148 -0
- package/runtime/guest_setup/vault/setup-guest-vault.sh +75 -0
- package/runtime/scripts/macos/setup-host.sh +126 -0
- package/runtime/scripts/remote_host_setup.sh +7 -4
- package/runtime/scripts/script_server.py +517 -0
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Serve the VAMP guest setup folder over HTTP so a guest installs it with wget or curl.
|
|
3
|
+
|
|
4
|
+
The VAMP host code no longer rewrites ISO images with xorriso. Guest setup
|
|
5
|
+
scripts, the recorder bundle and the vault helpers are staged into one folder
|
|
6
|
+
and served by Python's standard library on the fixed port 8421, which is not a
|
|
7
|
+
well-known port and is unlikely to collide with another service.
|
|
8
|
+
|
|
9
|
+
VirtualBox NAT and QEMU user networking both expose the host to the guest as
|
|
10
|
+
10.0.2.2; libvirt's default NAT network exposes it as 192.168.122.1.
|
|
11
|
+
|
|
12
|
+
python3 scripts/script_server.py start # stage + start, print JSON
|
|
13
|
+
python3 scripts/script_server.py status
|
|
14
|
+
python3 scripts/script_server.py stop
|
|
15
|
+
|
|
16
|
+
Guests then run:
|
|
17
|
+
|
|
18
|
+
wget -qO- http://10.0.2.2:8421/setup.sh | sh
|
|
19
|
+
powershell -ExecutionPolicy Bypass -Command "irm http://10.0.2.2:8421/setup.ps1 | iex"
|
|
20
|
+
|
|
21
|
+
The server only serves the staged setup folder (no directory listing, no
|
|
22
|
+
dotfiles) and stops itself after --ttl seconds (default 1800) unless stopped
|
|
23
|
+
sooner.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
import argparse
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import shutil
|
|
31
|
+
import signal
|
|
32
|
+
import socket
|
|
33
|
+
import subprocess
|
|
34
|
+
import sys
|
|
35
|
+
import tarfile
|
|
36
|
+
import threading
|
|
37
|
+
import time
|
|
38
|
+
import urllib.error
|
|
39
|
+
import urllib.request
|
|
40
|
+
import zipfile
|
|
41
|
+
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
|
|
44
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
45
|
+
SCRIPT_SERVER_PORT = 8421
|
|
46
|
+
DEFAULT_BIND = '0.0.0.0'
|
|
47
|
+
DEFAULT_TTL = 1800
|
|
48
|
+
SERVICE = 'vamp-script-server'
|
|
49
|
+
GUEST_HOSTS = {
|
|
50
|
+
'virtualbox_nat': '10.0.2.2',
|
|
51
|
+
'kvm_user_network': '10.0.2.2',
|
|
52
|
+
'kvm_default_network': '192.168.122.1',
|
|
53
|
+
}
|
|
54
|
+
SKIP = shutil.ignore_patterns('__pycache__', '*.pyc', '.git')
|
|
55
|
+
# The recorder bundle is committed to the repository so a clean checkout, a
|
|
56
|
+
# published package or a remote host can stage guest setup without the local
|
|
57
|
+
# third_party recorder sources. This URL is the last resort when neither the
|
|
58
|
+
# sources nor the committed bundle are present.
|
|
59
|
+
RECORDER_ZIP_URL = os.environ.get(
|
|
60
|
+
'VAMP_RECORDER_ZIP_URL',
|
|
61
|
+
'https://raw.githubusercontent.com/wayfarer6/vamp-mcp/main/guest_setup/recorder/recorder.zip',
|
|
62
|
+
)
|
|
63
|
+
RECORDER_ENTRY = 'PyAutoGuiRecorder.py'
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def state_directory() -> Path:
|
|
67
|
+
if os.environ.get('VAMP_SCRIPT_SERVER_DIR'):
|
|
68
|
+
return Path(os.environ['VAMP_SCRIPT_SERVER_DIR']).expanduser()
|
|
69
|
+
if os.environ.get('VAMP_DATA_DIR'):
|
|
70
|
+
return Path(os.environ['VAMP_DATA_DIR']).expanduser() / 'script-server'
|
|
71
|
+
return Path.home() / '.vamp' / 'script-server'
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _copy_tree(source: Path, destination: Path) -> None:
|
|
75
|
+
shutil.copytree(source, destination, ignore=SKIP, dirs_exist_ok=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _add_tree(archive: tarfile.TarFile, root: Path, name: str) -> None:
|
|
79
|
+
for path in sorted(root.rglob('*')):
|
|
80
|
+
if '__pycache__' in path.parts or path.suffix == '.pyc':
|
|
81
|
+
continue
|
|
82
|
+
archive.add(path, arcname=str(Path(name) / path.relative_to(root)))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _zip_tree(archive: zipfile.ZipFile, root: Path, name: str) -> None:
|
|
86
|
+
for path in sorted(root.rglob('*')):
|
|
87
|
+
if '__pycache__' in path.parts or path.suffix == '.pyc':
|
|
88
|
+
continue
|
|
89
|
+
archive.write(path, str(Path(name) / path.relative_to(root)))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def digest(path: Path) -> str:
|
|
93
|
+
with path.open('rb') as handle:
|
|
94
|
+
return hashlib.file_digest(handle, 'sha256').hexdigest()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _recorder_zip_usable(path: Path) -> bool:
|
|
98
|
+
"""True when path is a zip that carries the recorder program itself."""
|
|
99
|
+
try:
|
|
100
|
+
with zipfile.ZipFile(path) as archive:
|
|
101
|
+
return RECORDER_ENTRY in {Path(name).name for name in archive.namelist()}
|
|
102
|
+
except (OSError, zipfile.BadZipFile):
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def download_recorder_zip(destination: Path, url: str = RECORDER_ZIP_URL, timeout: int = 30) -> Path:
|
|
107
|
+
"""Fetch the committed recorder bundle when no local copy exists."""
|
|
108
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
request = urllib.request.Request(url, headers={'User-Agent': 'vamp-script-server'})
|
|
110
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
111
|
+
payload = response.read()
|
|
112
|
+
if not payload.startswith(b'PK'):
|
|
113
|
+
raise RuntimeError(f'{url} did not return a zip archive')
|
|
114
|
+
destination.write_bytes(payload)
|
|
115
|
+
if not _recorder_zip_usable(destination):
|
|
116
|
+
destination.unlink(missing_ok=True)
|
|
117
|
+
raise RuntimeError(f'{url} is not a usable recorder bundle (no {RECORDER_ENTRY})')
|
|
118
|
+
return destination
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def ensure_recorder_zip(folder: Path, recorder_source: Path | None = None) -> Path:
|
|
122
|
+
"""Keep recorder.zip beside the recorder setup.
|
|
123
|
+
|
|
124
|
+
Order: rebuild from the packaged recorder sources, reuse the bundle that
|
|
125
|
+
ships in the repository, then download it from the project's GitHub URL.
|
|
126
|
+
"""
|
|
127
|
+
recorder_zip = folder / 'recorder.zip'
|
|
128
|
+
if recorder_source and recorder_source.is_dir():
|
|
129
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
with zipfile.ZipFile(recorder_zip, 'w', zipfile.ZIP_DEFLATED) as archive:
|
|
131
|
+
for path in sorted(recorder_source.rglob('*')):
|
|
132
|
+
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc':
|
|
133
|
+
archive.write(path, str(path.relative_to(recorder_source)))
|
|
134
|
+
return recorder_zip
|
|
135
|
+
if _recorder_zip_usable(recorder_zip):
|
|
136
|
+
return recorder_zip
|
|
137
|
+
return download_recorder_zip(recorder_zip)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def stage(source: Path | None = None, destination: Path | None = None,
|
|
141
|
+
port: int = SCRIPT_SERVER_PORT) -> dict:
|
|
142
|
+
"""Build the served folder: HTTP bootstraps at the root plus the setup trees."""
|
|
143
|
+
source = Path(source or ROOT / 'guest_setup').expanduser().resolve()
|
|
144
|
+
if not (source / 'recorder' / 'setup.sh').is_file():
|
|
145
|
+
raise FileNotFoundError(f'Guest setup source is incomplete: {source}')
|
|
146
|
+
destination = Path(destination or state_directory() / 'stage').expanduser().resolve()
|
|
147
|
+
if destination.exists():
|
|
148
|
+
shutil.rmtree(destination)
|
|
149
|
+
destination.mkdir(parents=True)
|
|
150
|
+
|
|
151
|
+
http = source / 'http'
|
|
152
|
+
for name in ('setup.sh', 'postdeb.sh'):
|
|
153
|
+
shutil.copy2(http / name, destination / name)
|
|
154
|
+
(destination / name).chmod(0o755)
|
|
155
|
+
for name in ('setup.ps1', 'setup-all.ps1', 'setup-win.cmd', 'postwin.ps1'):
|
|
156
|
+
shutil.copy2(http / name, destination / name)
|
|
157
|
+
for name in ('setup-all.sh', 'setup-all.ps1'):
|
|
158
|
+
candidate = source / name
|
|
159
|
+
if candidate.is_file():
|
|
160
|
+
shutil.copy2(candidate, destination / name)
|
|
161
|
+
for name in ('recorder', 'vault', 'kvm'):
|
|
162
|
+
if (source / name).is_dir():
|
|
163
|
+
_copy_tree(source / name, destination / name)
|
|
164
|
+
|
|
165
|
+
# Guest setups expect recorder.zip beside setup.sh: rebuild it from the
|
|
166
|
+
# packaged recorder sources, otherwise keep the bundle committed in the
|
|
167
|
+
# repository, otherwise download it so a clean environment still works.
|
|
168
|
+
recorder_source = source.parent / 'third_party' / 'pyautogui-recorder'
|
|
169
|
+
try:
|
|
170
|
+
ensure_recorder_zip(destination / 'recorder', recorder_source)
|
|
171
|
+
except (OSError, RuntimeError, urllib.error.URLError) as error:
|
|
172
|
+
# A missing recorder only disables the recording tool, so keep serving
|
|
173
|
+
# the rest of guest setup and say plainly what is missing.
|
|
174
|
+
print(f'vamp: recorder bundle unavailable: {error}', file=sys.stderr)
|
|
175
|
+
|
|
176
|
+
# Optional verified VeraCrypt CLI payload for the vault setup.
|
|
177
|
+
cli_source = source.parent / 'artifacts' / 'kvm-setup' / 'bin'
|
|
178
|
+
if (cli_source / 'SHA256SUMS').is_file() and (cli_source / 'veracrypt.tar.gz').is_file():
|
|
179
|
+
(destination / 'cli').mkdir(exist_ok=True)
|
|
180
|
+
for name in ('SHA256SUMS', 'veracrypt.tar.gz'):
|
|
181
|
+
shutil.copy2(cli_source / name, destination / 'cli' / name)
|
|
182
|
+
|
|
183
|
+
tar_path = destination / 'vamp-guest-setup.tar.gz'
|
|
184
|
+
with tarfile.open(tar_path, 'w:gz') as archive:
|
|
185
|
+
for name in ('recorder', 'vault', 'kvm'):
|
|
186
|
+
if (destination / name).is_dir():
|
|
187
|
+
_add_tree(archive, destination / name, name)
|
|
188
|
+
if (destination / 'cli').is_dir():
|
|
189
|
+
_add_tree(archive, destination / 'cli', 'cli')
|
|
190
|
+
for name in ('setup-all.sh', 'setup-all.ps1'):
|
|
191
|
+
if (destination / name).is_file():
|
|
192
|
+
archive.add(destination / name, arcname=name)
|
|
193
|
+
|
|
194
|
+
zip_path = destination / 'vamp-guest-setup.zip'
|
|
195
|
+
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as archive:
|
|
196
|
+
for name in ('recorder', 'vault', 'kvm'):
|
|
197
|
+
if (destination / name).is_dir():
|
|
198
|
+
_zip_tree(archive, destination / name, name)
|
|
199
|
+
if (destination / 'cli').is_dir():
|
|
200
|
+
_zip_tree(archive, destination / 'cli', 'cli')
|
|
201
|
+
for name in ('setup-all.sh', 'setup-all.ps1'):
|
|
202
|
+
if (destination / name).is_file():
|
|
203
|
+
archive.write(destination / name, name)
|
|
204
|
+
|
|
205
|
+
commands = guest_commands(port)
|
|
206
|
+
manifest = {
|
|
207
|
+
'service': SERVICE,
|
|
208
|
+
'version': 1,
|
|
209
|
+
'port': port,
|
|
210
|
+
'guest_hosts': GUEST_HOSTS,
|
|
211
|
+
'bundles': {
|
|
212
|
+
'tar_gz': {'name': tar_path.name, 'sha256': digest(tar_path), 'bytes': tar_path.stat().st_size},
|
|
213
|
+
'zip': {'name': zip_path.name, 'sha256': digest(zip_path), 'bytes': zip_path.stat().st_size},
|
|
214
|
+
},
|
|
215
|
+
'commands': commands,
|
|
216
|
+
'note': 'Guest setup is downloaded, not installed: verify the guest after running it.',
|
|
217
|
+
}
|
|
218
|
+
(destination / 'vamp-setup.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
|
219
|
+
files = sorted(
|
|
220
|
+
str(path.relative_to(destination)).replace(os.sep, '/')
|
|
221
|
+
for path in destination.rglob('*') if path.is_file()
|
|
222
|
+
)
|
|
223
|
+
return {'status': 'staged', 'directory': str(destination), 'files': files, 'manifest': manifest}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def guest_commands(port: int = SCRIPT_SERVER_PORT, host: str = '10.0.2.2') -> dict:
|
|
227
|
+
base = f'http://{host}:{port}'
|
|
228
|
+
return {
|
|
229
|
+
'base_url': base,
|
|
230
|
+
'debian_recorder': f'wget -qO- {base}/setup.sh | sh',
|
|
231
|
+
'debian_recorder_curl': f'curl -fsSL {base}/setup.sh | sh',
|
|
232
|
+
'debian_all': f'wget -qO- {base}/setup.sh | sh -s -- --all',
|
|
233
|
+
'windows_recorder': f'powershell -ExecutionPolicy Bypass -Command "irm {base}/setup.ps1 | iex"',
|
|
234
|
+
'windows_cmd': f'curl.exe -fsSL {base}/setup-win.cmd -o %TEMP%\\setup-win.cmd && %TEMP%\\setup-win.cmd',
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class ScriptRequestHandler(SimpleHTTPRequestHandler):
|
|
239
|
+
"""Serve only the staged setup folder; no listings, no dotfiles, no caching."""
|
|
240
|
+
server_version = 'VAMPScriptServer/1.0'
|
|
241
|
+
extensions_map = {
|
|
242
|
+
**SimpleHTTPRequestHandler.extensions_map,
|
|
243
|
+
'.sh': 'text/plain; charset=utf-8',
|
|
244
|
+
'.ps1': 'text/plain; charset=utf-8',
|
|
245
|
+
'.cmd': 'text/plain; charset=utf-8',
|
|
246
|
+
'.json': 'application/json',
|
|
247
|
+
'.gz': 'application/gzip',
|
|
248
|
+
'.zip': 'application/zip',
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
def end_headers(self) -> None:
|
|
252
|
+
self.send_header('Cache-Control', 'no-store')
|
|
253
|
+
self.send_header('X-Content-Type-Options', 'nosniff')
|
|
254
|
+
super().end_headers()
|
|
255
|
+
|
|
256
|
+
def list_directory(self, path): # noqa: D401 - stdlib hook
|
|
257
|
+
self.send_error(404, 'Directory listing is disabled')
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
def translate_path(self, path: str) -> str:
|
|
261
|
+
resolved = super().translate_path(path)
|
|
262
|
+
root = Path(self.directory).resolve()
|
|
263
|
+
candidate = Path(resolved).resolve()
|
|
264
|
+
if root not in candidate.parents and candidate != root:
|
|
265
|
+
return str(root / '__forbidden__')
|
|
266
|
+
if any(part.startswith('.') for part in candidate.relative_to(root).parts):
|
|
267
|
+
return str(root / '__forbidden__')
|
|
268
|
+
return str(candidate)
|
|
269
|
+
|
|
270
|
+
def do_GET(self) -> None: # noqa: N802 - stdlib name
|
|
271
|
+
if self.path.split('?', 1)[0] == '/healthz':
|
|
272
|
+
payload = json.dumps({
|
|
273
|
+
'status': 'ok',
|
|
274
|
+
'service': SERVICE,
|
|
275
|
+
'port': self.server.server_address[1],
|
|
276
|
+
'directory': str(self.server.stage_directory),
|
|
277
|
+
'started_at': self.server.started_at,
|
|
278
|
+
'ttl_seconds': self.server.ttl,
|
|
279
|
+
}).encode()
|
|
280
|
+
self.send_response(200)
|
|
281
|
+
self.send_header('Content-Type', 'application/json')
|
|
282
|
+
self.send_header('Content-Length', str(len(payload)))
|
|
283
|
+
self.end_headers()
|
|
284
|
+
self.wfile.write(payload)
|
|
285
|
+
return
|
|
286
|
+
if self.path.split('?', 1)[0] == '/':
|
|
287
|
+
self.path = '/vamp-setup.json'
|
|
288
|
+
super().do_GET()
|
|
289
|
+
|
|
290
|
+
def log_message(self, format: str, *args) -> None: # noqa: A002 - stdlib name
|
|
291
|
+
sys.stderr.write(f'{time.strftime("%Y-%m-%d %H:%M:%S")} {self.address_string()} {format % args}\n')
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def make_server(directory: Path, port: int = SCRIPT_SERVER_PORT, bind: str = DEFAULT_BIND,
|
|
295
|
+
ttl: int = DEFAULT_TTL) -> ThreadingHTTPServer:
|
|
296
|
+
handler = lambda *args, **kwargs: ScriptRequestHandler(*args, directory=str(directory), **kwargs) # noqa: E731
|
|
297
|
+
server = ThreadingHTTPServer((bind, port), handler)
|
|
298
|
+
server.stage_directory = Path(directory)
|
|
299
|
+
server.started_at = time.strftime('%Y-%m-%dT%H:%M:%S%z')
|
|
300
|
+
server.ttl = ttl
|
|
301
|
+
return server
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def serve(directory: Path, port: int, bind: str, ttl: int) -> int:
|
|
305
|
+
try:
|
|
306
|
+
server = make_server(directory, port, bind, ttl)
|
|
307
|
+
except OSError as error:
|
|
308
|
+
sys.stderr.write(f'Cannot listen on {bind}:{port}: {error}\n')
|
|
309
|
+
return 2
|
|
310
|
+
stopping = threading.Event()
|
|
311
|
+
|
|
312
|
+
def stop(*_args) -> None:
|
|
313
|
+
if stopping.is_set():
|
|
314
|
+
return
|
|
315
|
+
stopping.set()
|
|
316
|
+
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
317
|
+
|
|
318
|
+
signal.signal(signal.SIGTERM, stop)
|
|
319
|
+
signal.signal(signal.SIGINT, stop)
|
|
320
|
+
if ttl > 0:
|
|
321
|
+
timer = threading.Timer(ttl, stop)
|
|
322
|
+
timer.daemon = True
|
|
323
|
+
timer.start()
|
|
324
|
+
sys.stderr.write(json.dumps({
|
|
325
|
+
'status': 'serving', 'service': SERVICE, 'port': server.server_address[1],
|
|
326
|
+
'bind': bind, 'directory': str(directory), 'ttl_seconds': ttl,
|
|
327
|
+
}) + '\n')
|
|
328
|
+
sys.stderr.flush()
|
|
329
|
+
try:
|
|
330
|
+
server.serve_forever(poll_interval=0.5)
|
|
331
|
+
finally:
|
|
332
|
+
server.server_close()
|
|
333
|
+
return 0
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _pid_file(port: int = SCRIPT_SERVER_PORT) -> Path:
|
|
337
|
+
return state_directory() / f'{port}.pid'
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _log_file(port: int = SCRIPT_SERVER_PORT) -> Path:
|
|
341
|
+
return state_directory() / f'{port}.log'
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _health(port: int) -> dict | None:
|
|
345
|
+
url = f'http://127.0.0.1:{port}/healthz'
|
|
346
|
+
try:
|
|
347
|
+
with urllib.request.urlopen(url, timeout=1.5) as response:
|
|
348
|
+
payload = json.loads(response.read())
|
|
349
|
+
except (urllib.error.URLError, OSError, ValueError):
|
|
350
|
+
return None
|
|
351
|
+
if isinstance(payload, dict) and payload.get('service') == SERVICE:
|
|
352
|
+
return payload
|
|
353
|
+
return {'status': 'foreign', 'service': payload.get('service') if isinstance(payload, dict) else None}
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def status(port: int = SCRIPT_SERVER_PORT) -> dict:
|
|
357
|
+
pid_path = _pid_file(port)
|
|
358
|
+
record: dict = {}
|
|
359
|
+
if pid_path.is_file():
|
|
360
|
+
try:
|
|
361
|
+
record = json.loads(pid_path.read_text())
|
|
362
|
+
except ValueError:
|
|
363
|
+
record = {}
|
|
364
|
+
health = _health(port)
|
|
365
|
+
if health and health.get('status') == 'ok':
|
|
366
|
+
return {'status': 'running', 'port': port, 'url': f'http://127.0.0.1:{port}',
|
|
367
|
+
'guest_urls': {name: f'http://{host}:{port}' for name, host in GUEST_HOSTS.items()},
|
|
368
|
+
'directory': health.get('directory'), 'started_at': health.get('started_at'),
|
|
369
|
+
'ttl_seconds': health.get('ttl_seconds'), 'pid': record.get('pid'),
|
|
370
|
+
'log': str(_log_file(port))}
|
|
371
|
+
if health and health.get('status') == 'foreign':
|
|
372
|
+
return {'status': 'port_in_use', 'port': port,
|
|
373
|
+
'error': f'Port {port} is already used by another service. Stop it before starting the VAMP script server.'}
|
|
374
|
+
if record.get('pid') and _alive(int(record['pid'])):
|
|
375
|
+
return {'status': 'starting', 'port': port, 'pid': record.get('pid'),
|
|
376
|
+
'log': str(_log_file(port))}
|
|
377
|
+
return {'status': 'stopped', 'port': port}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _alive(pid: int) -> bool:
|
|
381
|
+
if os.name == 'posix':
|
|
382
|
+
try:
|
|
383
|
+
os.kill(pid, 0)
|
|
384
|
+
except OSError:
|
|
385
|
+
return False
|
|
386
|
+
return True
|
|
387
|
+
# os.kill(pid, 0) terminates a process on Windows, so query the handle instead.
|
|
388
|
+
try:
|
|
389
|
+
import ctypes
|
|
390
|
+
handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
391
|
+
if not handle:
|
|
392
|
+
return False
|
|
393
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
394
|
+
return True
|
|
395
|
+
except Exception:
|
|
396
|
+
return True
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _terminate(pid: int) -> None:
|
|
400
|
+
if os.name == 'posix':
|
|
401
|
+
try:
|
|
402
|
+
os.kill(pid, signal.SIGTERM)
|
|
403
|
+
except OSError:
|
|
404
|
+
pass
|
|
405
|
+
return
|
|
406
|
+
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True, timeout=15)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _wait_health(port: int, seconds: float = 10.0) -> dict | None:
|
|
410
|
+
deadline = time.time() + seconds
|
|
411
|
+
while time.time() < deadline:
|
|
412
|
+
health = _health(port)
|
|
413
|
+
if health and health.get('status') == 'ok':
|
|
414
|
+
return health
|
|
415
|
+
time.sleep(0.2)
|
|
416
|
+
return None
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def start(source: Path | None = None, port: int = SCRIPT_SERVER_PORT, bind: str = DEFAULT_BIND,
|
|
420
|
+
ttl: int = DEFAULT_TTL) -> dict:
|
|
421
|
+
current = status(port)
|
|
422
|
+
if current['status'] == 'running':
|
|
423
|
+
return {**current, 'reused': True}
|
|
424
|
+
if current['status'] == 'port_in_use':
|
|
425
|
+
return current
|
|
426
|
+
staged = stage(source, port=port)
|
|
427
|
+
state = state_directory()
|
|
428
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
429
|
+
directory = Path(staged['directory'])
|
|
430
|
+
log_path = _log_file(port)
|
|
431
|
+
detach = {'start_new_session': True} if os.name == 'posix' else {
|
|
432
|
+
'creationflags': getattr(subprocess, 'DETACHED_PROCESS', 0) | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0)}
|
|
433
|
+
with log_path.open('ab') as log:
|
|
434
|
+
process = subprocess.Popen(
|
|
435
|
+
[sys.executable, str(Path(__file__).resolve()), 'serve',
|
|
436
|
+
'--directory', str(directory), '--port', str(port), '--bind', bind, '--ttl', str(ttl)],
|
|
437
|
+
stdout=log, stderr=log, stdin=subprocess.DEVNULL, **detach,
|
|
438
|
+
)
|
|
439
|
+
health = _wait_health(port)
|
|
440
|
+
if not health:
|
|
441
|
+
return {'status': 'failed', 'port': port,
|
|
442
|
+
'error': f'The script server did not answer on port {port}. Read {log_path}.'}
|
|
443
|
+
record = {'pid': process.pid, 'port': port, 'bind': bind, 'directory': str(directory),
|
|
444
|
+
'started_at': health.get('started_at'), 'ttl_seconds': ttl}
|
|
445
|
+
_pid_file(port).write_text(json.dumps(record, indent=2) + '\n')
|
|
446
|
+
return {'status': 'running', 'port': port, 'pid': process.pid, 'bind': bind,
|
|
447
|
+
'directory': str(directory), 'started_at': health.get('started_at'), 'ttl_seconds': ttl,
|
|
448
|
+
'url': f'http://127.0.0.1:{port}',
|
|
449
|
+
'guest_urls': {name: f'http://{host}:{port}' for name, host in GUEST_HOSTS.items()},
|
|
450
|
+
'commands': guest_commands(port), 'manifest': str(directory / 'vamp-setup.json'),
|
|
451
|
+
'log': str(log_path)}
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def stop(port: int = SCRIPT_SERVER_PORT) -> dict:
|
|
455
|
+
pid_path = _pid_file(port)
|
|
456
|
+
record: dict = {}
|
|
457
|
+
if pid_path.is_file():
|
|
458
|
+
try:
|
|
459
|
+
record = json.loads(pid_path.read_text())
|
|
460
|
+
except ValueError:
|
|
461
|
+
record = {}
|
|
462
|
+
pid = record.get('pid')
|
|
463
|
+
if not pid:
|
|
464
|
+
if status(port)['status'] == 'running':
|
|
465
|
+
return {'status': 'running', 'port': port,
|
|
466
|
+
'error': 'A script server answers on this port but its pid file is missing. Stop it from the terminal that started it.'}
|
|
467
|
+
return {'status': 'stopped', 'port': port}
|
|
468
|
+
pid = int(pid)
|
|
469
|
+
_terminate(pid)
|
|
470
|
+
deadline = time.time() + 6
|
|
471
|
+
while time.time() < deadline and _alive(pid):
|
|
472
|
+
time.sleep(0.2)
|
|
473
|
+
if _alive(pid) and os.name == 'posix':
|
|
474
|
+
try:
|
|
475
|
+
os.kill(pid, signal.SIGKILL)
|
|
476
|
+
except OSError:
|
|
477
|
+
pass
|
|
478
|
+
pid_path.unlink(missing_ok=True)
|
|
479
|
+
return {'status': 'stopped', 'port': port, 'pid': pid}
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def free_port() -> int:
|
|
483
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
484
|
+
probe.bind(('127.0.0.1', 0))
|
|
485
|
+
return probe.getsockname()[1]
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def main(argv: list[str] | None = None) -> int:
|
|
489
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
490
|
+
parser.add_argument('command', choices=('serve', 'stage', 'start', 'stop', 'status'))
|
|
491
|
+
parser.add_argument('--port', type=int, default=SCRIPT_SERVER_PORT,
|
|
492
|
+
help=f'HTTP port; VAMP uses {SCRIPT_SERVER_PORT} (default)')
|
|
493
|
+
parser.add_argument('--bind', default=DEFAULT_BIND, help=f'Bind address (default {DEFAULT_BIND})')
|
|
494
|
+
parser.add_argument('--directory', help='Guest setup source folder (default: <repo>/guest_setup)')
|
|
495
|
+
parser.add_argument('--ttl', type=int, default=DEFAULT_TTL, help='Seconds before the server stops itself (0 = no limit)')
|
|
496
|
+
parser.add_argument('--json', action='store_true', help='Print one JSON document on stdout')
|
|
497
|
+
args = parser.parse_args(argv)
|
|
498
|
+
source = Path(args.directory) if args.directory else None
|
|
499
|
+
|
|
500
|
+
if args.command == 'serve':
|
|
501
|
+
if not args.directory:
|
|
502
|
+
parser.error('serve needs --directory (run "start" to stage and launch)')
|
|
503
|
+
return serve(Path(args.directory), args.port, args.bind, args.ttl)
|
|
504
|
+
if args.command == 'stage':
|
|
505
|
+
result = stage(source, port=args.port)
|
|
506
|
+
elif args.command == 'start':
|
|
507
|
+
result = start(source, args.port, args.bind, args.ttl)
|
|
508
|
+
elif args.command == 'stop':
|
|
509
|
+
result = stop(args.port)
|
|
510
|
+
else:
|
|
511
|
+
result = status(args.port)
|
|
512
|
+
print(json.dumps(result, indent=2))
|
|
513
|
+
return 0 if result.get('status') not in ('failed', 'port_in_use') else 1
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
if __name__ == '__main__':
|
|
517
|
+
sys.exit(main())
|