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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""Exercise production daemon service commands on a private systemd user unit.
Run inside nix develop after building cli/bin/albedo. ALBEDO_TEST_DAEMON mayselect an exec-only snapshot instead of a packaged daemon. Requires a user bus."""
import hashlibimport jsonimport osfrom pathlib import Pathimport signalimport subprocessimport sysimport tempfileimport threadingimport unittest
ROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT / "test/e2e"))from harness import Albedo, Provider, alive, python, text, wait_until, exclusive # noqa: E402
def run(): actual_config = Path( os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")) ) cells = []
def script(request): if request["input"][-1].get("role") == "user" and cells: return python(cells.pop(0)) return text("done")
with tempfile.TemporaryDirectory(prefix="albedo service % $ ") as directory: executable = Path(directory) / "albedo % $" executable.symlink_to(ROOT / "cli/bin/albedo")
def prepare(app): app.env.pop("ALBEDO_SYSTEMCTL", None) app.env.pop("ALBEDO_PARENT_PID", None) app.env["XDG_CONFIG_HOME"] = str(actual_config) app.env["ALBEDO_TEST_CLI"] = str(executable) app.env["ALBEDO_ROOT"] = str(Path(directory) / "root with % $ `") app.daemon.boot_action = lambda daemon: daemon.cli("daemon", "install")
provider = Provider(script) app = Albedo(provider, protocol="responses", prepare=prepare) unit = None home = None try: app.__enter__() home = app.home unit = ( "systems.albedo.daemon-" + hashlib.sha256(str(home).encode()).hexdigest()[:16] + ".service" )
def state(): output = subprocess.check_output( [ "systemctl", "--user", "show", unit, "-p", "MainPID", "-p", "ActiveState", "-p", "NRestarts", ], text=True, ) return dict(line.split("=", 1) for line in output.splitlines())
def cell(code): cells.append(code) app.prompt(session, "run it").close() app.idle(session) return [ json.loads(part["value"]) for entry in app.history(session)["items"] if entry["kind"] == "tool_result" and entry["tool"]["name"] == "python" for part in entry["content"] if part["kind"] == "json" and part["field"] == "result" ][-1]
session = app.session() first = cell( "hold = run('sleep', '120')\nimport os\nsurvivor = 41\nos.getpid()" ) kernel_pid = int(first["value"]) assert int(state()["MainPID"]) == app.connection["pid"] original = app.connection["pid"] app.cli("daemon", "install") assert app.connection["pid"] == original assert int(state()["MainPID"]) == original restarts = state()["NRestarts"] app.cli("daemon", "--stop") assert state()["ActiveState"] == "inactive" assert state()["NRestarts"] == restarts assert alive(kernel_pid) app.daemon.connection = None app.cli("daemon") app.daemon.await_ready() adopted = cell("survivor += 1\n(survivor, os.getpid())") assert adopted["value"] == f"(42, {kernel_pid})", adopted subprocess.run(["systemctl", "--user", "stop", unit], check=True) assert alive(kernel_pid) app.daemon.connection = None app.cli("daemon") app.daemon.await_ready() adopted = cell("survivor += 1\n(survivor, os.getpid())") assert adopted["value"] == f"(43, {kernel_pid})", adopted app.cli("daemon", "--stop", "--kernels") wait_until(lambda: not alive(kernel_pid), 10, "kernel survived --kernels") assert state()["ActiveState"] == "inactive" app.daemon.connection = None app.cli("daemon") app.daemon.await_ready() assert cell("survivor")["value"] == "43" old = app.connection["pid"] os.kill(old, signal.SIGKILL) wait_until( lambda: int(state()["MainPID"]) not in (0, old), 20, "service did not restart after crash", ) app.daemon.connection = None app.daemon.await_ready() app.cli("daemon", "--stop", "--kernels") direct = subprocess.Popen( [app.env["ALBEDO_DAEMON"]], env=app.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) threading.Thread(target=direct.wait, daemon=True).start() try: app.daemon.connection = None app.daemon.await_ready() subprocess.run( ["systemctl", "--user", "reset-failed", unit], check=True ) subprocess.run( ["systemctl", "--user", "start", unit], check=False, capture_output=True, ) wait_until( lambda: state()["ActiveState"] == "failed", 10, "contended service did not fail", ) status = subprocess.check_output( [ "systemctl", "--user", "show", unit, "-p", "ExecMainStatus", "-p", "NRestarts", ], text=True, ) assert "ExecMainStatus=75" in status and "NRestarts=0" in status, status app.cli("daemon", "--stop", "--kernels") direct.wait(timeout=10) finally: if direct.poll() is None: direct.terminate() direct.wait(timeout=20) app.cli("daemon", "uninstall") app.cli("daemon") app.daemon.connection = None app.daemon.await_ready() assert int(state()["MainPID"]) == 0 app.cli("daemon", "--stop", "--kernels") print( "real systemd installation, refresh, shutdown, kernel adoption/save, crash restart and uninstall passed" ) finally: # Only this fixture's conventional unit and processes are touched. if home is None and getattr(app, "home", None) is not None: home = app.home if unit is None and home is not None: unit = ( "systems.albedo.daemon-" + hashlib.sha256(str(home).encode()).hexdigest()[:16] + ".service" ) if unit is not None: subprocess.run( ["systemctl", "--user", "stop", unit], capture_output=True ) subprocess.run( ["systemctl", "--user", "disable", unit], capture_output=True ) (actual_config / "systemd/user" / unit).unlink(missing_ok=True) subprocess.run( ["systemctl", "--user", "daemon-reload"], capture_output=True ) subprocess.run( ["systemctl", "--user", "reset-failed", unit], capture_output=True ) app.__exit__(None, None, None) provider.close()
@exclusiveclass RealServiceTests(unittest.TestCase): def test_native_service_lifecycle(self): run()
if __name__ == "__main__": raise SystemExit( subprocess.run( [ sys.executable, str(ROOT / "test/e2e/run.py"), str(Path(__file__).resolve()), ] ).returncode )