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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""A daemon booted through a standby VM is the daemon a cold boot gives.
Catches a handover that changes the daemon (its home, storage or log), a CLIthat takes a standby it must not (a refusing or dead one, one another CLIalready took) and a standby that outlives the process that started it. Onlythe real CLI, standby and daemon together show these. A standby of anotherbuild is refused on both sides by tier-1 tests: the CLI's record selection incli/internal/localdaemon/homelock_unix_test.go and the standby's digest checkin apps/albedo/test/albedo/lifecycle/standby_environment_test.gleam."""
import jsonimport osfrom pathlib import Pathimport shutilimport signalimport subprocessimport tempfileimport threadingimport unittest
import harnessfrom harness import Albedo, Provider, alive, text, wait_until
def snapshot(): assert harness._executable is not None, "the runner snapshots the daemon first" return Path(harness._executable).parent
def snapshot_digest(): return (snapshot() / "albedo" / ".build-digest-v2").read_text().strip()
class Standbys: """A private standby directory, so no other test takes this test's standby."""
def __init__(self, test): self.test = test self.dir = Path(tempfile.mkdtemp(prefix="sb-", dir="/tmp")) test.addCleanup(self.stop)
def daemon(self, name, **env): daemon = harness.Daemon(name) daemon.env["ALBEDO_STANDBY_DIR"] = str(self.dir) daemon.env.update(env) self.test.addCleanup(daemon.shutdown) return daemon
def records(self): records = [] for path in self.dir.glob("*.json"): try: records.append(json.loads(path.read_text())) except (OSError, ValueError): pass return records
def ready(self, other_than=()): """The live standby of a build once its socket is up.""" digest = snapshot_digest() found = {}
def listening(): for record in self.records(): if ( record["digest"] == digest and record["pid"] not in other_than and alive(record["pid"]) and os.path.exists(record["socket"]) ): found.update(record) return True return False
wait_until(listening, 30, "no standby came up") return found
def stop(self): for record in self.records(): try: os.kill(record["pid"], signal.SIGKILL) except ProcessLookupError: pass shutil.rmtree(self.dir, ignore_errors=True)
def pid(daemon): return json.loads((daemon.home / "daemon.json").read_text())["pid"]
class StandbyTests(unittest.TestCase): def setUp(self): self.standbys = Standbys(self)
def test_a_boot_through_a_standby_keeps_its_sessions_like_a_cold_one(self): first = self.standbys.daemon("first") first.boot() standby = self.standbys.ready() second = self.standbys.daemon("second") second.boot() self.assertEqual(pid(second), standby["pid"]) self.assertFalse(os.path.exists(standby["socket"])) record = json.loads((second.home / "daemon.json").read_text()) self.assertEqual(record["digest"], snapshot_digest()) # The CLI left the next launch a standby of its own, and of two # launches racing for it exactly one takes it. left = self.standbys.ready(other_than={standby["pid"]}) racers = [self.standbys.daemon(f"racer-{n}") for n in range(2)] failures = []
def boot(daemon): try: daemon.boot() except BaseException as error: failures.append(error)
threads = [threading.Thread(target=boot, args=(daemon,)) for daemon in racers] for thread in threads: thread.start() for thread in threads: thread.join() self.assertEqual(failures, []) pids = [pid(daemon) for daemon in racers] self.assertEqual(pids.count(left["pid"]), 1, pids) self.assertEqual(len(set(pids)), 2, pids)
provider = Provider(lambda _: text("from the handed-over daemon")) try: with harness.on_daemon(second), Albedo(provider) as app: session = app.session() app.prompt(session, "hello").close() app.idle(session) self.assertTrue(provider.requests) second.restart() self.assertIn( "from the handed-over daemon", json.dumps(app.history(session)) ) finally: provider.close() self.assertTrue((second.home / "albedo.sqlite").exists()) log = (second.home / "daemon.log").read_bytes() self.assertTrue(log) self.assertNotIn(b"\0", log)
def test_a_launch_without_a_usable_standby_boots_cold(self): digest = snapshot_digest() # A record whose standby died: its pid is gone and nothing listens. gone = subprocess.Popen(["true"]) gone.wait() socket = self.standbys.dir / f"{digest[:16]}-{gone.pid}.sock" (self.standbys.dir / f"{digest[:16]}.json").write_text( json.dumps({"pid": gone.pid, "digest": digest, "socket": str(socket)}) ) dead = self.standbys.daemon("dead") dead.boot() self.assertNotEqual(pid(dead), gone.pid) standby = self.standbys.ready() # The VM started with other flags than this CLI asks for: it refuses # and exits, and the CLI boots cold. refused = self.standbys.daemon("refused", ERL_AFLAGS="+hms 233") refused.boot() self.assertNotEqual(pid(refused), standby["pid"]) wait_until(lambda: not alive(standby["pid"]), 10, "the refusing standby stayed") missing = self.standbys.daemon("missing", ALBEDO_STANDBY="0") missing.boot() self.assertNotIn( pid(missing), {record["pid"] for record in self.standbys.records()} )
def test_a_standby_ends_with_the_process_that_started_it(self): parent = subprocess.Popen(["sleep", "120"]) self.addCleanup(parent.kill) daemon = self.standbys.daemon("parented", ALBEDO_PARENT_PID=str(parent.pid)) daemon.boot() standby = self.standbys.ready() parent.kill() parent.wait() wait_until( lambda: not alive(standby["pid"]), 15, "the standby outlived its parent" ) wait_until( lambda: not list(self.standbys.dir.iterdir()), 5, "the standby left files behind", )
if __name__ == "__main__": unittest.main()