harlequin-sqlite-ssh 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.
- harlequin_sqlite_ssh/__init__.py +12 -0
- harlequin_sqlite_ssh/_agent.py +693 -0
- harlequin_sqlite_ssh/adapter.py +362 -0
- harlequin_sqlite_ssh/cli_options.py +105 -0
- harlequin_sqlite_ssh/errors.py +71 -0
- harlequin_sqlite_ssh/locations.py +219 -0
- harlequin_sqlite_ssh/py.typed +0 -0
- harlequin_sqlite_ssh/remote.py +359 -0
- harlequin_sqlite_ssh/transport.py +723 -0
- harlequin_sqlite_ssh-0.1.0.dist-info/METADATA +164 -0
- harlequin_sqlite_ssh-0.1.0.dist-info/RECORD +14 -0
- harlequin_sqlite_ssh-0.1.0.dist-info/WHEEL +4 -0
- harlequin_sqlite_ssh-0.1.0.dist-info/entry_points.txt +2 -0
- harlequin_sqlite_ssh-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
"""Start the remote agent over SSH and exchange messages with it.
|
|
2
|
+
|
|
3
|
+
The adapter does not open a socket or a port forward: SQLite is a file, and
|
|
4
|
+
nothing on the remote host listens for it. Instead, `AgentProcess` runs the
|
|
5
|
+
`ssh` client found on PATH with a remote command that starts the remote
|
|
6
|
+
`python3` and feeds it the agent's source (`_agent.py`) on stdin. From then
|
|
7
|
+
on, stdin and stdout of that `ssh` process carry the newline-delimited JSON
|
|
8
|
+
protocol described in `_agent.py`.
|
|
9
|
+
|
|
10
|
+
Security choices, all made here:
|
|
11
|
+
|
|
12
|
+
- `ssh` runs with ``BatchMode=yes``: Harlequin's TUI owns the terminal by the
|
|
13
|
+
time the adapter connects, so `ssh` could not ask for a passphrase, a
|
|
14
|
+
password or a host key anyway. Authentication must come from a key, an
|
|
15
|
+
`ssh-agent`, or a shared master connection (``ControlMaster``).
|
|
16
|
+
- Agent and X11 forwarding are turned off (``-a -x``) and forwardings declared
|
|
17
|
+
in `~/.ssh/config` are cleared, since none of them is needed to query a
|
|
18
|
+
file.
|
|
19
|
+
- Values that end up on the `ssh` command line are validated first, because a
|
|
20
|
+
`harlequin.toml` in the current directory, possibly from a cloned
|
|
21
|
+
repository, can set them (see `validate_ssh_option`).
|
|
22
|
+
- The remote Python runs in isolated mode (``-I``), so a `sqlite3.py` or
|
|
23
|
+
`json.py` left in the remote home directory is never imported.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import base64
|
|
29
|
+
import json
|
|
30
|
+
import math
|
|
31
|
+
import queue
|
|
32
|
+
import re
|
|
33
|
+
import shlex
|
|
34
|
+
import sqlite3
|
|
35
|
+
import subprocess
|
|
36
|
+
import threading
|
|
37
|
+
from collections import deque
|
|
38
|
+
from collections.abc import Sequence
|
|
39
|
+
from dataclasses import dataclass, field
|
|
40
|
+
from importlib import resources
|
|
41
|
+
from typing import IO, Any
|
|
42
|
+
|
|
43
|
+
from harlequin_sqlite_ssh import _agent
|
|
44
|
+
from harlequin_sqlite_ssh.errors import (
|
|
45
|
+
AgentStartError,
|
|
46
|
+
ConnectionLostError,
|
|
47
|
+
error_from_wire,
|
|
48
|
+
)
|
|
49
|
+
from harlequin_sqlite_ssh.locations import RemoteTarget
|
|
50
|
+
|
|
51
|
+
SSH = "ssh"
|
|
52
|
+
"""The client, found on PATH, as Harlequin's own SSH tunnels use it."""
|
|
53
|
+
|
|
54
|
+
BOOTSTRAP = (
|
|
55
|
+
"import sys,base64;"
|
|
56
|
+
"exec(compile(base64.b64decode(sys.stdin.buffer.readline()),"
|
|
57
|
+
"'harlequin-sqlite-ssh-agent','exec'))"
|
|
58
|
+
)
|
|
59
|
+
"""The one-liner the remote Python runs: read one line of base64 from stdin,
|
|
60
|
+
and execute it as the agent. The rest of stdin is then the protocol."""
|
|
61
|
+
|
|
62
|
+
DEFAULT_PYTHON = "python3"
|
|
63
|
+
"""The remote interpreter, unless `remote_python` names another."""
|
|
64
|
+
|
|
65
|
+
MAX_TIMEOUT = 3600.0
|
|
66
|
+
"""The longest `remote_timeout` accepted: an hour. Waits beyond what the
|
|
67
|
+
platform's clock types hold would raise OverflowError."""
|
|
68
|
+
|
|
69
|
+
DEFAULT_TIMEOUT = 60.0
|
|
70
|
+
"""Seconds to wait for the agent's hello, as long as Harlequin's own SSH
|
|
71
|
+
timeout, because a slow `ProxyJump` chain is a reason to wait, not to fail."""
|
|
72
|
+
|
|
73
|
+
KEEPALIVE_SECONDS = 30
|
|
74
|
+
"""`ServerAliveInterval` set where the SSH configuration resolves it to 0
|
|
75
|
+
(OpenSSH's default), so that an idle session behind a NAT is not dropped
|
|
76
|
+
silently. The same value Harlequin uses for its tunnels."""
|
|
77
|
+
|
|
78
|
+
KEEPALIVE_COUNT = 3
|
|
79
|
+
"""`ServerAliveCountMax` that goes with `KEEPALIVE_SECONDS`."""
|
|
80
|
+
|
|
81
|
+
STDERR_LINES = 40
|
|
82
|
+
"""How many of the last stderr lines are kept to explain a failure."""
|
|
83
|
+
|
|
84
|
+
NOISE_LINES = 200
|
|
85
|
+
"""How many stdout lines that are not the hello may come first (a remote shell
|
|
86
|
+
startup file that prints something) before the handshake gives up."""
|
|
87
|
+
|
|
88
|
+
ALLOWED_SSH_OPTIONS = {
|
|
89
|
+
key.lower(): key
|
|
90
|
+
for key in (
|
|
91
|
+
"AddressFamily",
|
|
92
|
+
"BindAddress",
|
|
93
|
+
"Ciphers",
|
|
94
|
+
"Compression",
|
|
95
|
+
"ConnectTimeout",
|
|
96
|
+
"ConnectionAttempts",
|
|
97
|
+
"HostKeyAlgorithms",
|
|
98
|
+
"HostName",
|
|
99
|
+
"IdentitiesOnly",
|
|
100
|
+
"IdentityFile",
|
|
101
|
+
"IPQoS",
|
|
102
|
+
"KexAlgorithms",
|
|
103
|
+
"LogLevel",
|
|
104
|
+
"MACs",
|
|
105
|
+
"Port",
|
|
106
|
+
"PreferredAuthentications",
|
|
107
|
+
"ProxyJump",
|
|
108
|
+
"PubkeyAcceptedAlgorithms",
|
|
109
|
+
"ServerAliveCountMax",
|
|
110
|
+
"ServerAliveInterval",
|
|
111
|
+
"TCPKeepAlive",
|
|
112
|
+
"User",
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
"""The `ssh -o` keywords `remote_ssh_option` may set, lowercased to their
|
|
116
|
+
canonical spelling.
|
|
117
|
+
|
|
118
|
+
An allow-list rather than a deny-list: several keywords run a local command
|
|
119
|
+
or load a local library (`ProxyCommand`, `LocalCommand`, `KnownHostsCommand`,
|
|
120
|
+
`PKCS11Provider`, `SecurityKeyProvider`, ...), and a config file found in the
|
|
121
|
+
current directory must not be able to set them.
|
|
122
|
+
|
|
123
|
+
Nothing that weakens host key verification is allowed either
|
|
124
|
+
(`StrictHostKeyChecking`, `UserKnownHostsFile`, `HostKeyAlias`,
|
|
125
|
+
`CheckHostIP`, `UpdateHostKeys`), nor anything that points `ssh` at a local
|
|
126
|
+
socket (`ControlPath`, `ControlMaster`, `ControlPersist`, `IdentityAgent`):
|
|
127
|
+
with them, such a config file could send queries, and the init script read
|
|
128
|
+
from this machine, to a host the user never accepted. Anything else still
|
|
129
|
+
works from `~/.ssh/config`, which only its owner writes.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
_SSH_OPTION = re.compile(r"^\s*([A-Za-z][A-Za-z0-9]*)\s*(?:=|\s)\s*(\S.*?)\s*$")
|
|
133
|
+
_SAFE_PYTHON = re.compile(r"^[A-Za-z0-9_./+~-]+$")
|
|
134
|
+
_SAFE_SSH_VALUE = re.compile(r"^[A-Za-z0-9_.,:@%~/+\[\]-]+$")
|
|
135
|
+
"""What an option value may hold: no space, quote, or shell metacharacter.
|
|
136
|
+
|
|
137
|
+
`ssh` can paste a value into a command its shell runs: `ProxyJump` becomes
|
|
138
|
+
a `ProxyCommand`, and `HostName` or `User` fill the ``%h`` and ``%r`` of a
|
|
139
|
+
`ProxyCommand` from `~/.ssh/config`. A path with a space must therefore be
|
|
140
|
+
set in `~/.ssh/config`.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
_NO_LEADING_DASH = {"HostName", "ProxyJump", "User"}
|
|
144
|
+
"""Keywords whose value `ssh` may pass on as a command-line argument, where a
|
|
145
|
+
leading ``-`` would read as an option."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def validate_ssh_option(raw: str) -> str:
|
|
149
|
+
"""Check one `remote_ssh_option` and return it as ``Keyword=value``.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
raw: An option as `ssh -o` takes it, ``Keyword=value`` or
|
|
153
|
+
``Keyword value``.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
The option with its keyword in canonical case.
|
|
157
|
+
|
|
158
|
+
Raises:
|
|
159
|
+
ValueError: If the option is malformed, holds a control character,
|
|
160
|
+
or uses a keyword outside `ALLOWED_SSH_OPTIONS`.
|
|
161
|
+
"""
|
|
162
|
+
if any(ord(character) < 32 for character in raw):
|
|
163
|
+
raise ValueError(f"SSH option {raw!r} contains a control character.")
|
|
164
|
+
match = _SSH_OPTION.match(raw)
|
|
165
|
+
if match is None:
|
|
166
|
+
raise ValueError(
|
|
167
|
+
f"SSH option {raw!r} is not of the form Keyword=value, as ssh -o takes it."
|
|
168
|
+
)
|
|
169
|
+
keyword, value = match.groups()
|
|
170
|
+
canonical = ALLOWED_SSH_OPTIONS.get(keyword.lower())
|
|
171
|
+
if canonical is None:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"SSH option {keyword} cannot be set by this adapter. Allowed: "
|
|
174
|
+
f"{', '.join(sorted(ALLOWED_SSH_OPTIONS.values()))}. "
|
|
175
|
+
"Set anything else in ~/.ssh/config."
|
|
176
|
+
)
|
|
177
|
+
if not _SAFE_SSH_VALUE.match(value):
|
|
178
|
+
raise ValueError(
|
|
179
|
+
f"SSH option {canonical}: {value!r} may only hold letters, digits and "
|
|
180
|
+
"_ . , : @ % ~ / + [ ] -. Set values with spaces or other characters "
|
|
181
|
+
"in ~/.ssh/config."
|
|
182
|
+
)
|
|
183
|
+
if canonical in _NO_LEADING_DASH and any(
|
|
184
|
+
part.startswith("-") for part in re.split(r"[,@]", value)
|
|
185
|
+
):
|
|
186
|
+
raise ValueError(f"SSH option {canonical}: {value!r} must not start with -.")
|
|
187
|
+
return f"{canonical}={value}"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def validate_timeout(raw: str | float) -> float:
|
|
191
|
+
"""Check the `remote_timeout` value and return it in seconds.
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
raw: A number of seconds, as a string (CLI, TOML) or a number.
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
The timeout as a float.
|
|
198
|
+
|
|
199
|
+
Raises:
|
|
200
|
+
ValueError: If it is not a number, or not more than 0 and at most
|
|
201
|
+
`MAX_TIMEOUT`: a longer wait would overflow the platform's clock
|
|
202
|
+
types.
|
|
203
|
+
"""
|
|
204
|
+
try:
|
|
205
|
+
seconds = float(raw)
|
|
206
|
+
except (TypeError, ValueError):
|
|
207
|
+
raise ValueError(
|
|
208
|
+
f"remote_timeout {raw!r} is not a number of seconds."
|
|
209
|
+
) from None
|
|
210
|
+
if not (math.isfinite(seconds) and 0 < seconds <= MAX_TIMEOUT):
|
|
211
|
+
raise ValueError(
|
|
212
|
+
f"remote_timeout must be a number of seconds above 0 and at most "
|
|
213
|
+
f"{MAX_TIMEOUT:g}, not {raw!r}."
|
|
214
|
+
)
|
|
215
|
+
return seconds
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def validate_python(raw: str) -> str:
|
|
219
|
+
"""Check the `remote_python` value and return it.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
raw: An executable name or path on the remote host, e.g. ``python3``
|
|
223
|
+
or ``/opt/python/bin/python3.12``.
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
`raw`, unchanged.
|
|
227
|
+
|
|
228
|
+
Raises:
|
|
229
|
+
ValueError: If it is empty, starts with ``-``, or holds anything but
|
|
230
|
+
letters, digits and ``_ . / + ~ -``. It is shell-quoted anyway;
|
|
231
|
+
the check keeps it to an executable rather than a command line.
|
|
232
|
+
"""
|
|
233
|
+
if not raw or raw.startswith("-") or not _SAFE_PYTHON.match(raw):
|
|
234
|
+
raise ValueError(
|
|
235
|
+
f"remote_python {raw!r} must be an executable name or path, such as "
|
|
236
|
+
"python3 or /usr/bin/python3.11."
|
|
237
|
+
)
|
|
238
|
+
return raw
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def remote_command(python: str) -> str:
|
|
242
|
+
"""Return the command line `ssh` asks the remote shell to run.
|
|
243
|
+
|
|
244
|
+
`ssh` joins its remaining arguments with spaces and hands them to the
|
|
245
|
+
remote user's login shell, so every word is quoted for a POSIX shell.
|
|
246
|
+
"""
|
|
247
|
+
return " ".join(["exec", shlex.quote(python), "-I", "-c", shlex.quote(BOOTSTRAP)])
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def agent_payload() -> bytes:
|
|
251
|
+
"""Return the agent's source as the base64 line the bootstrap reads."""
|
|
252
|
+
text = resources.files("harlequin_sqlite_ssh").joinpath("_agent.py").read_bytes()
|
|
253
|
+
return base64.b64encode(text) + b"\n"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def ssh_base_argv(target: RemoteTarget, options: Sequence[str]) -> list[str]:
|
|
257
|
+
"""Return the `ssh` arguments shared by the session and `ssh -G`.
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
target: Where to connect.
|
|
261
|
+
options: Validated ``Keyword=value`` options.
|
|
262
|
+
|
|
263
|
+
Returns:
|
|
264
|
+
The argument list without the destination.
|
|
265
|
+
"""
|
|
266
|
+
argv = [SSH, "-o", "BatchMode=yes"]
|
|
267
|
+
for option in options:
|
|
268
|
+
argv += ["-o", option]
|
|
269
|
+
if target.port is not None:
|
|
270
|
+
argv += ["-p", str(target.port)]
|
|
271
|
+
return argv
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def needs_keepalive(target: RemoteTarget, options: Sequence[str]) -> bool:
|
|
275
|
+
"""Tell whether the SSH configuration leaves `ServerAliveInterval` at 0.
|
|
276
|
+
|
|
277
|
+
Asks `ssh -G`, which prints the configuration it would use without
|
|
278
|
+
connecting, so that a value from `~/.ssh/config` is respected: an option
|
|
279
|
+
on the command line would override it.
|
|
280
|
+
|
|
281
|
+
Returns:
|
|
282
|
+
True if keepalives are off, False if they are on or `ssh -G` could not
|
|
283
|
+
say (the real connection then reports the problem).
|
|
284
|
+
"""
|
|
285
|
+
argv = [*ssh_base_argv(target, options), "-G", "--", target.destination]
|
|
286
|
+
try:
|
|
287
|
+
result = subprocess.run(
|
|
288
|
+
argv,
|
|
289
|
+
stdin=subprocess.DEVNULL,
|
|
290
|
+
capture_output=True,
|
|
291
|
+
text=True,
|
|
292
|
+
timeout=10,
|
|
293
|
+
check=False,
|
|
294
|
+
)
|
|
295
|
+
except (OSError, subprocess.SubprocessError):
|
|
296
|
+
return False
|
|
297
|
+
if result.returncode != 0:
|
|
298
|
+
return False
|
|
299
|
+
for line in result.stdout.splitlines():
|
|
300
|
+
key, _, value = line.partition(" ")
|
|
301
|
+
if key.lower() == "serveraliveinterval":
|
|
302
|
+
return value.strip() == "0"
|
|
303
|
+
return False
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def session_argv(
|
|
307
|
+
target: RemoteTarget, python: str, options: Sequence[str], keepalive: bool
|
|
308
|
+
) -> list[str]:
|
|
309
|
+
"""Return the full `ssh` command that starts the agent on `target`.
|
|
310
|
+
|
|
311
|
+
Args:
|
|
312
|
+
target: Where to connect.
|
|
313
|
+
python: The validated remote interpreter.
|
|
314
|
+
options: Validated ``Keyword=value`` options.
|
|
315
|
+
keepalive: Whether to add `ServerAliveInterval` and
|
|
316
|
+
`ServerAliveCountMax` (see `needs_keepalive`).
|
|
317
|
+
"""
|
|
318
|
+
argv = ssh_base_argv(target, options)
|
|
319
|
+
argv += ["-T", "-a", "-x", "-o", "ClearAllForwardings=yes"]
|
|
320
|
+
if keepalive:
|
|
321
|
+
argv += [
|
|
322
|
+
"-o",
|
|
323
|
+
f"ServerAliveInterval={KEEPALIVE_SECONDS}",
|
|
324
|
+
"-o",
|
|
325
|
+
f"ServerAliveCountMax={KEEPALIVE_COUNT}",
|
|
326
|
+
]
|
|
327
|
+
argv += ["--", target.destination, remote_command(python)]
|
|
328
|
+
return argv
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
@dataclass
|
|
332
|
+
class Hello:
|
|
333
|
+
"""What the agent reported about the remote host in its handshake."""
|
|
334
|
+
|
|
335
|
+
python: str
|
|
336
|
+
"""The remote Python version, e.g. ``3.11.2``."""
|
|
337
|
+
sqlite: str
|
|
338
|
+
"""The SQLite library version the remote Python links."""
|
|
339
|
+
autocommit: bool
|
|
340
|
+
"""Whether `sqlite3.Connection.autocommit` exists (Python 3.12+)."""
|
|
341
|
+
load_extension: bool
|
|
342
|
+
"""Whether the remote sqlite3 module can load extensions."""
|
|
343
|
+
noise: list[str] = field(default_factory=list)
|
|
344
|
+
"""Lines printed on stdout before the hello, by a shell startup file."""
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
class AgentProcess:
|
|
348
|
+
"""A running agent, and the only way to talk to it.
|
|
349
|
+
|
|
350
|
+
Requests are serialized: `request()` holds a lock from writing a request
|
|
351
|
+
to reading its answer, so threads may share one instance. `interrupt()`
|
|
352
|
+
does not take that lock, which is what lets it stop a request that is
|
|
353
|
+
holding it.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
def __init__(self, argv: Sequence[str], description: str) -> None:
|
|
357
|
+
"""Start the process; `handshake()` must be called next.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
argv: The command to run, from `session_argv()` (or a local
|
|
361
|
+
Python, in tests).
|
|
362
|
+
description: How error messages name the other end, e.g.
|
|
363
|
+
``user@host``.
|
|
364
|
+
|
|
365
|
+
Raises:
|
|
366
|
+
AgentStartError: If the command cannot be started at all.
|
|
367
|
+
"""
|
|
368
|
+
self.description = description
|
|
369
|
+
self._stderr: deque[str] = deque(maxlen=STDERR_LINES)
|
|
370
|
+
self._lines: queue.Queue[bytes | None] = queue.Queue()
|
|
371
|
+
self._request_lock = threading.Lock()
|
|
372
|
+
self._write_lock = threading.Lock()
|
|
373
|
+
self._in_flight: int | None = None
|
|
374
|
+
self._next_id = 1
|
|
375
|
+
self._closed = False
|
|
376
|
+
self._broken: str | None = None
|
|
377
|
+
"""Why the session cannot be used any more, once it cannot."""
|
|
378
|
+
try:
|
|
379
|
+
self._process = subprocess.Popen(
|
|
380
|
+
list(argv),
|
|
381
|
+
stdin=subprocess.PIPE,
|
|
382
|
+
stdout=subprocess.PIPE,
|
|
383
|
+
stderr=subprocess.PIPE,
|
|
384
|
+
start_new_session=True,
|
|
385
|
+
)
|
|
386
|
+
except OSError as e:
|
|
387
|
+
raise AgentStartError(f"Could not run {argv[0]}: {e}") from e
|
|
388
|
+
assert self._process.stdout is not None
|
|
389
|
+
assert self._process.stderr is not None
|
|
390
|
+
threading.Thread(
|
|
391
|
+
target=self._pump_stdout,
|
|
392
|
+
args=(self._process.stdout,),
|
|
393
|
+
name="harlequin-sqlite-ssh-stdout",
|
|
394
|
+
daemon=True,
|
|
395
|
+
).start()
|
|
396
|
+
threading.Thread(
|
|
397
|
+
target=self._pump_stderr,
|
|
398
|
+
args=(self._process.stderr,),
|
|
399
|
+
name="harlequin-sqlite-ssh-stderr",
|
|
400
|
+
daemon=True,
|
|
401
|
+
).start()
|
|
402
|
+
|
|
403
|
+
# -- lifecycle ----------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
def handshake(self, payload: bytes, timeout: float) -> Hello:
|
|
406
|
+
"""Send the agent's source and wait for its hello.
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
payload: The line `agent_payload()` returns.
|
|
410
|
+
timeout: Seconds to wait for the hello.
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
What the agent reported.
|
|
414
|
+
|
|
415
|
+
Raises:
|
|
416
|
+
AgentStartError: If the process exits, the timeout expires, too
|
|
417
|
+
many other lines come first, or the agent speaks another
|
|
418
|
+
protocol version. The message quotes `ssh`'s stderr.
|
|
419
|
+
"""
|
|
420
|
+
# One deadline for sending the agent and hearing back: the write is
|
|
421
|
+
# done in a thread, because it blocks until the other end reads it,
|
|
422
|
+
# which `ssh` only does once connected, and a pipe may hold less than
|
|
423
|
+
# the agent's source.
|
|
424
|
+
deadline = _Deadline(validate_timeout(timeout))
|
|
425
|
+
writer = threading.Thread(
|
|
426
|
+
target=self._send_payload,
|
|
427
|
+
args=(payload,),
|
|
428
|
+
name="harlequin-sqlite-ssh-bootstrap",
|
|
429
|
+
daemon=True,
|
|
430
|
+
)
|
|
431
|
+
writer.start()
|
|
432
|
+
try:
|
|
433
|
+
return self._await_hello(deadline, timeout)
|
|
434
|
+
except BaseException:
|
|
435
|
+
# whatever went wrong, no ssh process is left behind
|
|
436
|
+
if self.alive:
|
|
437
|
+
self.kill()
|
|
438
|
+
raise
|
|
439
|
+
|
|
440
|
+
def _await_hello(self, deadline: _Deadline, timeout: float) -> Hello:
|
|
441
|
+
"""Read stdout until the hello, skipping shell noise; see `handshake`."""
|
|
442
|
+
noise: list[str] = []
|
|
443
|
+
while True:
|
|
444
|
+
try:
|
|
445
|
+
line = self._lines.get(timeout=deadline.remaining())
|
|
446
|
+
except queue.Empty:
|
|
447
|
+
self.kill()
|
|
448
|
+
raise AgentStartError(
|
|
449
|
+
self._explain(f"no answer from the agent after {timeout:g} seconds")
|
|
450
|
+
) from None
|
|
451
|
+
if line is None:
|
|
452
|
+
self._wait_exit(1.0)
|
|
453
|
+
raise AgentStartError(self._explain("the connection closed", noise))
|
|
454
|
+
hello = _parse_hello(line)
|
|
455
|
+
if hello is None:
|
|
456
|
+
noise.append(line.decode("utf-8", "replace").rstrip())
|
|
457
|
+
if len(noise) > NOISE_LINES:
|
|
458
|
+
self.kill()
|
|
459
|
+
raise AgentStartError(
|
|
460
|
+
self._explain("the agent never answered", noise)
|
|
461
|
+
)
|
|
462
|
+
continue
|
|
463
|
+
if hello.get("protocol") != _agent.PROTOCOL_VERSION:
|
|
464
|
+
self.kill()
|
|
465
|
+
raise AgentStartError(
|
|
466
|
+
f"The agent on {self.description} speaks protocol "
|
|
467
|
+
f"{hello.get('protocol')!r}, not {_agent.PROTOCOL_VERSION}."
|
|
468
|
+
)
|
|
469
|
+
return Hello(
|
|
470
|
+
python=str(hello.get("python", "?")),
|
|
471
|
+
sqlite=str(hello.get("sqlite", "?")),
|
|
472
|
+
autocommit=bool(hello.get("autocommit")),
|
|
473
|
+
load_extension=bool(hello.get("load_extension")),
|
|
474
|
+
noise=noise,
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
def _send_payload(self, payload: bytes) -> None:
|
|
478
|
+
"""Write the agent's source; a failure shows up as end of output."""
|
|
479
|
+
try:
|
|
480
|
+
self._write(payload)
|
|
481
|
+
except ConnectionLostError:
|
|
482
|
+
pass
|
|
483
|
+
|
|
484
|
+
def close(self, timeout: float = 3.0) -> None:
|
|
485
|
+
"""Ask the agent to close the database, then end the process.
|
|
486
|
+
|
|
487
|
+
Never raises: this runs when Harlequin quits. A request in flight is
|
|
488
|
+
interrupted first; if its lock is still not free after `timeout`, the
|
|
489
|
+
process is killed instead.
|
|
490
|
+
"""
|
|
491
|
+
if self._closed:
|
|
492
|
+
return
|
|
493
|
+
self.interrupt()
|
|
494
|
+
if self._request_lock.acquire(timeout=timeout):
|
|
495
|
+
try:
|
|
496
|
+
self._send_close(timeout)
|
|
497
|
+
finally:
|
|
498
|
+
self._request_lock.release()
|
|
499
|
+
self._closed = True
|
|
500
|
+
try:
|
|
501
|
+
assert self._process.stdin is not None
|
|
502
|
+
self._process.stdin.close()
|
|
503
|
+
except OSError:
|
|
504
|
+
pass
|
|
505
|
+
if not self._wait_exit(timeout):
|
|
506
|
+
self.kill()
|
|
507
|
+
|
|
508
|
+
def kill(self) -> None:
|
|
509
|
+
"""End the process at once, without asking the agent."""
|
|
510
|
+
self._closed = True
|
|
511
|
+
if self._process.poll() is None:
|
|
512
|
+
self._process.kill()
|
|
513
|
+
self._wait_exit(2.0)
|
|
514
|
+
|
|
515
|
+
@property
|
|
516
|
+
def alive(self) -> bool:
|
|
517
|
+
"""Whether the `ssh` process is still running."""
|
|
518
|
+
return self._process.poll() is None
|
|
519
|
+
|
|
520
|
+
# -- requests -----------------------------------------------------------
|
|
521
|
+
|
|
522
|
+
def request(self, op: str, **arguments: Any) -> Any:
|
|
523
|
+
"""Send one request and return its result.
|
|
524
|
+
|
|
525
|
+
Args:
|
|
526
|
+
op: The operation, an ``op_*`` method of the agent.
|
|
527
|
+
**arguments: The request's other keys.
|
|
528
|
+
|
|
529
|
+
Returns:
|
|
530
|
+
The `result` the agent answered with.
|
|
531
|
+
|
|
532
|
+
Raises:
|
|
533
|
+
sqlite3.Error: The error SQLite raised on the remote host, as the
|
|
534
|
+
same class (see `errors.error_from_wire`).
|
|
535
|
+
ConnectionLostError: If the process is gone or the answer cannot
|
|
536
|
+
be read.
|
|
537
|
+
"""
|
|
538
|
+
with self._request_lock:
|
|
539
|
+
if self._broken is not None:
|
|
540
|
+
raise ConnectionLostError(self._broken)
|
|
541
|
+
if self._closed:
|
|
542
|
+
raise ConnectionLostError(
|
|
543
|
+
f"The connection to {self.description} is closed."
|
|
544
|
+
)
|
|
545
|
+
request_id = self._next_id
|
|
546
|
+
self._next_id += 1
|
|
547
|
+
message = {"id": request_id, "op": op, **arguments}
|
|
548
|
+
try:
|
|
549
|
+
with self._write_lock:
|
|
550
|
+
# in flight only once written: an interrupt sent earlier
|
|
551
|
+
# would name a request the agent has not seen, and be lost
|
|
552
|
+
self._write_unlocked(_encode(message))
|
|
553
|
+
self._in_flight = request_id
|
|
554
|
+
answer = self._read_answer(request_id, timeout=None)
|
|
555
|
+
except ConnectionLostError as e:
|
|
556
|
+
# Lost, or out of step with the agent: every later answer
|
|
557
|
+
# would be read as the answer to the wrong request.
|
|
558
|
+
self._broken = str(e)
|
|
559
|
+
self.kill()
|
|
560
|
+
raise
|
|
561
|
+
finally:
|
|
562
|
+
with self._write_lock:
|
|
563
|
+
self._in_flight = None
|
|
564
|
+
if answer.get("ok"):
|
|
565
|
+
return answer.get("result")
|
|
566
|
+
raise error_from_wire(answer.get("error") or {})
|
|
567
|
+
|
|
568
|
+
def interrupt(self) -> None:
|
|
569
|
+
"""Stop the request in flight, if there is one.
|
|
570
|
+
|
|
571
|
+
Safe to call from any thread, including while another thread waits
|
|
572
|
+
in `request()`. Does nothing when no request is in flight, so that it
|
|
573
|
+
cannot stop the next one.
|
|
574
|
+
"""
|
|
575
|
+
with self._write_lock:
|
|
576
|
+
target = self._in_flight
|
|
577
|
+
if target is None or self._closed:
|
|
578
|
+
return
|
|
579
|
+
try:
|
|
580
|
+
self._write_unlocked(_encode({"op": "interrupt", "target": target}))
|
|
581
|
+
except ConnectionLostError:
|
|
582
|
+
pass
|
|
583
|
+
|
|
584
|
+
# -- internals ----------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
def _send_close(self, timeout: float) -> None:
|
|
587
|
+
"""Send a ``close`` request and wait up to `timeout` for its answer."""
|
|
588
|
+
request_id = self._next_id
|
|
589
|
+
self._next_id += 1
|
|
590
|
+
try:
|
|
591
|
+
with self._write_lock:
|
|
592
|
+
self._write_unlocked(_encode({"id": request_id, "op": "close"}))
|
|
593
|
+
self._read_answer(request_id, timeout=timeout)
|
|
594
|
+
except sqlite3.Error:
|
|
595
|
+
pass
|
|
596
|
+
|
|
597
|
+
def _read_answer(self, request_id: int, timeout: float | None) -> dict[str, Any]:
|
|
598
|
+
"""Wait for the answer to `request_id` and return it decoded."""
|
|
599
|
+
try:
|
|
600
|
+
line = self._lines.get(timeout=timeout)
|
|
601
|
+
except queue.Empty:
|
|
602
|
+
raise ConnectionLostError(
|
|
603
|
+
self._explain(f"no answer within {timeout:g} seconds")
|
|
604
|
+
) from None
|
|
605
|
+
if line is None:
|
|
606
|
+
# keep the end-of-output marker for whoever reads next
|
|
607
|
+
self._lines.put(None)
|
|
608
|
+
raise ConnectionLostError(self._explain("the connection was lost"))
|
|
609
|
+
try:
|
|
610
|
+
answer = json.loads(line.decode("utf-8"))
|
|
611
|
+
except ValueError:
|
|
612
|
+
raise ConnectionLostError(
|
|
613
|
+
self._explain(
|
|
614
|
+
"the agent sent something that is not a protocol message: "
|
|
615
|
+
f"{line[:200]!r}"
|
|
616
|
+
)
|
|
617
|
+
) from None
|
|
618
|
+
if not isinstance(answer, dict) or answer.get("id") != request_id:
|
|
619
|
+
raise ConnectionLostError(
|
|
620
|
+
self._explain(f"the agent answered out of order: {line[:200]!r}")
|
|
621
|
+
)
|
|
622
|
+
return answer
|
|
623
|
+
|
|
624
|
+
def _write(self, data: bytes) -> None:
|
|
625
|
+
"""Write `data` to the agent's stdin, under the write lock."""
|
|
626
|
+
with self._write_lock:
|
|
627
|
+
self._write_unlocked(data)
|
|
628
|
+
|
|
629
|
+
def _write_unlocked(self, data: bytes) -> None:
|
|
630
|
+
"""Write `data`; the caller holds the write lock."""
|
|
631
|
+
stdin = self._process.stdin
|
|
632
|
+
assert stdin is not None
|
|
633
|
+
try:
|
|
634
|
+
stdin.write(data)
|
|
635
|
+
stdin.flush()
|
|
636
|
+
except (OSError, ValueError) as e:
|
|
637
|
+
# Close the pipe now: left open with unwritten data, it would
|
|
638
|
+
# raise BrokenPipeError again when garbage-collected.
|
|
639
|
+
try:
|
|
640
|
+
stdin.close()
|
|
641
|
+
except (OSError, ValueError):
|
|
642
|
+
pass
|
|
643
|
+
raise ConnectionLostError(self._explain("the connection was lost")) from e
|
|
644
|
+
|
|
645
|
+
def _pump_stdout(self, stream: IO[bytes]) -> None:
|
|
646
|
+
"""Move stdout lines to the queue; None marks the end."""
|
|
647
|
+
try:
|
|
648
|
+
for line in stream:
|
|
649
|
+
self._lines.put(line)
|
|
650
|
+
except (OSError, ValueError):
|
|
651
|
+
pass
|
|
652
|
+
finally:
|
|
653
|
+
self._lines.put(None)
|
|
654
|
+
|
|
655
|
+
def _pump_stderr(self, stream: IO[bytes]) -> None:
|
|
656
|
+
"""Keep the last stderr lines, to quote them in error messages."""
|
|
657
|
+
try:
|
|
658
|
+
for line in stream:
|
|
659
|
+
text = line.decode("utf-8", "replace").rstrip()
|
|
660
|
+
if text:
|
|
661
|
+
self._stderr.append(text)
|
|
662
|
+
except (OSError, ValueError):
|
|
663
|
+
pass
|
|
664
|
+
|
|
665
|
+
def _wait_exit(self, timeout: float) -> bool:
|
|
666
|
+
"""Wait up to `timeout` for the process to end; tell whether it did."""
|
|
667
|
+
try:
|
|
668
|
+
self._process.wait(timeout=timeout)
|
|
669
|
+
except subprocess.TimeoutExpired:
|
|
670
|
+
return False
|
|
671
|
+
return True
|
|
672
|
+
|
|
673
|
+
def _explain(self, what: str, noise: Sequence[str] = ()) -> str:
|
|
674
|
+
"""Build an error message: what happened, exit status, and stderr."""
|
|
675
|
+
parts = [f"SSH session to {self.description}: {what}."]
|
|
676
|
+
code = self._process.poll()
|
|
677
|
+
if code is not None:
|
|
678
|
+
parts.append(f"ssh exited with status {code}.")
|
|
679
|
+
if code == 127:
|
|
680
|
+
parts.append(
|
|
681
|
+
"Status 127 usually means the remote Python was not found; "
|
|
682
|
+
"set remote_python to its path."
|
|
683
|
+
)
|
|
684
|
+
if self._stderr:
|
|
685
|
+
parts.append("stderr:\n" + "\n".join(self._stderr))
|
|
686
|
+
if noise:
|
|
687
|
+
parts.append(
|
|
688
|
+
"Lines printed on stdout before the agent started (a shell "
|
|
689
|
+
"startup file must not print anything for a non-interactive "
|
|
690
|
+
"session):\n" + "\n".join(list(noise)[:10])
|
|
691
|
+
)
|
|
692
|
+
return "\n".join(parts)
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
class _Deadline:
|
|
696
|
+
"""Seconds left until a fixed point in time."""
|
|
697
|
+
|
|
698
|
+
def __init__(self, seconds: float) -> None:
|
|
699
|
+
import time
|
|
700
|
+
|
|
701
|
+
self._time = time.monotonic
|
|
702
|
+
self._end = self._time() + seconds
|
|
703
|
+
|
|
704
|
+
def remaining(self) -> float:
|
|
705
|
+
"""Seconds left, never negative."""
|
|
706
|
+
return max(0.0, self._end - self._time())
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _encode(message: dict[str, Any]) -> bytes:
|
|
710
|
+
"""Encode one protocol message as a JSON line."""
|
|
711
|
+
text = json.dumps(message, separators=(",", ":"), ensure_ascii=False)
|
|
712
|
+
return text.encode("utf-8") + b"\n"
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _parse_hello(line: bytes) -> dict[str, Any] | None:
|
|
716
|
+
"""Return the hello message on `line`, or None if it is something else."""
|
|
717
|
+
try:
|
|
718
|
+
message = json.loads(line.decode("utf-8"))
|
|
719
|
+
except ValueError:
|
|
720
|
+
return None
|
|
721
|
+
if isinstance(message, dict) and message.get("hello") == _agent.HELLO:
|
|
722
|
+
return message
|
|
723
|
+
return None
|