"""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 (another build, 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. """ 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").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, digest=None, other_than=()): """The live standby of a build once its socket is up.""" digest = digest or 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. self.standbys.ready(other_than={standby["pid"]}) 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_of_another_build_is_never_used(self): launcher, other = other_build(Path(tempfile.mkdtemp(prefix="build-"))) self.addCleanup(shutil.rmtree, launcher.parent, True) first = self.standbys.daemon("other-build", ALBEDO_DAEMON=str(launcher)) first.boot() foreign = self.standbys.ready(digest=other) current = self.standbys.daemon("current") current.boot() self.assertNotEqual(pid(current), foreign["pid"]) self.assertTrue(alive(foreign["pid"])) self.assertTrue(os.path.exists(foreign["socket"])) def test_two_launches_racing_for_one_standby_hand_it_to_one(self): self.standbys.daemon("first").boot() standby = self.standbys.ready() 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(standby["pid"]), 1, pids) self.assertEqual(len(set(pids)), 2, pids) 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", ) def other_build(out): """The test snapshot under another sealed digest: the same code, which the CLI and its standby must treat as a different build.""" source = snapshot() for package in source.iterdir(): if package.is_dir() and package.name != "albedo": (out / package.name).symlink_to(package) albedo = out / "albedo" albedo.mkdir() for entry in ("ebin", "priv"): (albedo / entry).symlink_to((source / "albedo" / entry).resolve()) digest = "f" * 64 (albedo / ".build-digest").write_text(digest + "\n") launcher = out / "albedo-daemon" launcher.write_text( "#!/bin/sh\n" f"exec {harness.ROOT}/priv/bin/albedo-daemon erl -pa {out}/*/ebin " "-eval 'albedo@@main:run(albedo)' -noshell -extra \"$@\"\n" ) launcher.chmod(0o755) return launcher, digest if __name__ == "__main__": unittest.main()