"""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 CLI that takes a standby it must not (a refusing or dead one, one another CLI already took) and a standby that outlives the process that started it. Only the real CLI, standby and daemon together show these. A standby of another build is refused on both sides by tier-1 tests: the CLI's record selection in cli/internal/localdaemon/homelock_unix_test.go and the standby's digest check in apps/albedo/test/albedo/lifecycle/standby_environment_test.gleam. """ import json import os from pathlib import Path import shutil import signal import subprocess import tempfile import threading import unittest import harness from 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()