Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Moving sessions between two daemons: the loopback ssh a source daemonreaches its target through, and the transfer and move routes the scenariosdrive.
A move's source reaches the target over ssh. `loopback_ssh` puts an ssh onthe source daemon's PATH that runs each command on this machine, withALBEDO_HOME set to the home the `hosts` directory names for the target host,so the relay the move stages there calls that daemon. The host's login shellreads no profile, so the PATH the ssh sets is the host's.
The transfer helpers pump a move by hand, as the move's transport does:export on the source, stage on the target, send every segment, ready andactivate. The move helpers ask the source daemon to drive one instead."""
import jsonimport osimport shleximport shutilimport signalimport subprocessimport sysimport timeimport urllib.errorimport urllib.parseimport urllib.requestfrom dataclasses import dataclassfrom pathlib import Path
from harness import ROOT, operation_id
# An ssh whose every connection fails, as an unreachable host's does, while# the `down` switch exists.DOWN_SSH = """#!/bin/shquery=while [ $# -gt 0 ]; do case "$1" in -o) shift 2 ;; -G) query=1; shift ;; -*) shift ;; *) break ;; esacdonetarget=$1shift[ -n "$query" ] && exit 0if [ -e {down} ]; then echo "ssh: connect to host $target port 22: Network is unreachable" >&2 exit 255fiexec env -i HOME={home} ALBEDO_HOME="$(cat {hosts}/"$target")" PATH={path} SHELL={login} /bin/sh -c "$*""""
# The host's login shell. It sources no profile: /etc/profile may replace PATH# (NixOS's does), dropping the fake host's python3 for the system's or none.LOGIN_SHELL = """#!/bin/sh[ "$1" = -l ] && shiftexec /bin/sh "$@""""
# The size of the chunks a segment is sent to the target in.CHUNK = 524288
MOVE_SETTLED = ("checklist", "active", "failed")
def executable(path, content): path.write_text(content) path.chmod(0o755) return path
def remote_bin(directory): """The fake host's bin directory: python3 and nothing else of its own.""" directory.mkdir(exist_ok=True) os.symlink(shutil.which("python3") or sys.executable, directory / "python3") return directory
def login_shell(local): """Writes the host's login shell into `local` and answers its path.""" return executable(local / "loginsh", LOGIN_SHELL)
@dataclassclass Loopback: """Where a `loopback_ssh` keeps its hosts: each file in `hosts` names a host and holds the ALBEDO_HOME its commands run with; `remote_home` is the host's HOME, and while `down` exists the host is out of reach."""
remote_home: Path hosts: Path down: Path
def loopback_ssh(app, root): """Puts the `DOWN_SSH` loopback ssh ahead of the daemon's PATH, from an Albedo fixture's prepare. `root` holds the hosts and the down switch; the ssh, its login shell and the hosts' HOME stay under the daemon's root for an exclusive class's later tests.""" loopback = Loopback(app.root / "remote-home", root / "hosts", root / "down") loopback.hosts.mkdir() local = app.root / "local-bin" for directory in (loopback.remote_home, local): directory.mkdir(exist_ok=True) remote = remote_bin(root / "remote-bin") path = app.daemon.env["PATH"] executable( local / "ssh", DOWN_SSH.format( down=loopback.down, hosts=loopback.hosts, home=loopback.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), login=login_shell(local), ), ) app.daemon.env["PYTHONPATH"] = str(ROOT / "test/fixtures/uv_release") app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}" return loopback
def drop_relays(remote_home): """Ends the transfer relays running on this loopback host, the ones whose command line holds `remote_home`, as a dropped connection would. Relays of other tests and other gates on the machine keep running: a pattern that matched every relay would end their moves mid-call.""" listing = subprocess.run( ["ps", "-ww", "-eo", "pid=,args="], capture_output=True, text=True, check=True ).stdout home = os.path.join(remote_home, "") for line in listing.splitlines(): pid, _, args = line.strip().partition(" ") if "albedo_transfer_relay" in args and home in args: try: os.kill(int(pid), signal.SIGTERM) except ProcessLookupError: pass
def wait_for(predicate, timeout=60, message="condition not met", every=0.1): """The predicate's first true answer. `message` may be a function, read when the wait gives up.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(every) raise AssertionError(message() if callable(message) else message)
# ---- requests ---------------------------------------------------------------
class Refused(Exception): """A daemon's problem answer: status and decoded body."""
def __init__(self, code, body): super().__init__(f"{code}: {body}") self.code = code self.body = body
def request( daemon, method, path, data=None, content_type="application/json", headers=None): """A raw request, for bodies and answers that are not JSON objects, such as a transfer segment. A problem answer raises `Refused`.""" sent = {"Authorization": f"Bearer {daemon.connection['token']}", **(headers or {})} if data is not None: sent["Content-Type"] = content_type req = urllib.request.Request( daemon.base + path, data=data, method=method, headers=sent ) try: with urllib.request.urlopen(req, timeout=60) as response: return response.read() except urllib.error.HTTPError as failure: raise Refused(failure.code, json.loads(failure.read())) from None
def answer(daemon, method, path, body=None, headers=None): """A JSON request and its decoded answer.""" data = None if body is None else json.dumps(body).encode() return json.loads(request(daemon, method, path, data, headers=headers))
def refusal(call): """The status and problem body `call` was refused with.""" try: call() except Refused as refused: return refused.code, refused.body raise AssertionError("the request was not refused")
def idle(daemon, session, timeout=60, message=None): """The session's snapshot once it is idle with nothing pending. A daemon still opening the session answers 503, which is waited out."""
def settled(): try: snapshot = answer(daemon, "GET", f"/sessions/{session}?tail=0") except Refused as refused: if refused.code != 503: raise return None if snapshot["status"]["phase"] == "idle" and not snapshot["pending_inputs"]: return snapshot return None
return wait_for(settled, timeout, message or f"session {session} did not settle")
# ---- a transfer pumped by hand ------------------------------------------------
def export(source, transfer, session): """The manifest text of `session`'s export under `transfer`.""" return request( source, "POST", f"/transfers/{transfer}/export", json.dumps({"session_id": session}).encode(), )
def fetch(source, transfer, index, size): """Segment `index` of an export, `size` bytes, read in the source's chunks.""" data = b"" while len(data) < size: data += request( source, "GET", f"/transfers/{transfer}/export/segments/{index}?offset={len(data)}", ) return data
def exported(source, session, transfer=None): """Exports `session`: the transfer id, its manifest and every segment's bytes.""" transfer = transfer or operation_id() manifest = json.loads(export(source, transfer, session)) segments = [ fetch(source, transfer, index, segment["bytes"]) for index, segment in enumerate(manifest["segments"]) ] return transfer, manifest, segments
def stage(target, transfer, manifest_text, workspace): """Stages a manifest on the target, to activate into `workspace`.""" query = urllib.parse.urlencode({"workspace": str(workspace)}) return json.loads( request(target, "PUT", f"/transfers/{transfer}/import?{query}", manifest_text) )
def send(target, transfer, index, data): """Sends segment `index`'s bytes to the target in `CHUNK`s.""" for offset in range(0, len(data), CHUNK): request( target, "PUT", f"/transfers/{transfer}/import/segments/{index}?offset={offset}", data[offset : offset + CHUNK], "application/octet-stream", )
def ready(target, transfer): return answer(target, "POST", f"/transfers/{transfer}/import/ready")
def activate(target, transfer): return answer(target, "POST", f"/transfers/{transfer}/import/activate")
def import_status(target, transfer): return answer(target, "GET", f"/transfers/{transfer}/import")
def deliver(target, transfer, manifest_text, segments, workspace): """Stages the manifest into `workspace`, sends every segment and asks the target to ready it; answers the target's status after ready.""" stage(target, transfer, manifest_text, workspace) for index, data in enumerate(segments): send(target, transfer, index, data) return ready(target, transfer)
def find_segment(manifest, owner, name): """The index and entry of `owner`'s segment `name` in a manifest.""" return next( (i, s) for i, s in enumerate(manifest["segments"]) if s["owner"] == owner and s["name"] == name )
# ---- a move the source drives -----------------------------------------------
def preflight(source, session, target): query = urllib.parse.urlencode({"session_id": session, "target": target}) with source.api("/transfers/preflight?" + query) as response: return json.load(response)
def start_move(source, session, transfer, target, profiles=None): """Asks the source to move `session` to `target`; the move it answers.""" body = {"transfer_id": transfer, "target": target} if profiles is not None: body["profiles"] = profiles with source.api(f"/sessions/{session}/move", body) as response: if response.status != 202: raise AssertionError(f"the move answered {response.status}, not 202") return json.load(response)
def read_move(source, transfer): with source.api(f"/transfers/{transfer}") as response: return json.load(response)
def settled_move(source, transfer, timeout=90): """The move once it reaches its checklist, goes active or fails.""" return wait_for( lambda: (move := read_move(source, transfer))["state"] in MOVE_SETTLED and move, timeout, lambda: f"the move never settled: {read_move(source, transfer)}", )
def finish_move(source, transfer): with source.api(f"/transfers/{transfer}/finish", {}) as response: if response.status != 200: raise AssertionError(f"finish answered {response.status}, not 200") return json.load(response)