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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441#!/usr/bin/env python3"""Stand in for the login manager while running its real service command."""
import jsonimport osfrom pathlib import Pathimport plistlibimport shleximport signalimport subprocessimport sysimport time
root = Path(os.environ["ALBEDO_HOME"])args = [arg for arg in sys.argv[1:] if arg != "--user"]command = args[0]service_name = next( ( Path(arg).name.removesuffix(".plist") for arg in args if Path(arg).name.startswith("systems.albedo.") or Path(arg).name == "albedo.service" ), args[-1],)role = ( Path(service_name).name.split(".")[2].split("-")[0] if service_name.startswith("systems.albedo.") else "daemon" if service_name == "albedo.service" else "proxy")if command == "print-disabled": role = "daemon" import hashlib
service_name = ( "systems.albedo.daemon-" + hashlib.sha256(str(root).encode()).hexdigest()[:16] )state = root / (role + "-service-stub.json")with (root / "service-stub.log").open("a") as log: log.write(json.dumps(args) + "\n")if (root / "service-stub-fail").exists(): sys.exit("service manager unavailable")
# Share the canonical native output with the parser tests.DARWIN_PRINT = ( Path(__file__).resolve().parents[2] / "internal/loginservice/testdata/launchd/idle.txt").read_text()# Substitute the loaded argument list rather than assuming a direct command.argument_prefix, _, argument_tail = DARWIN_PRINT.partition("\targuments = {\n")_, _, argument_suffix = argument_tail.partition("\n\t}\n")DARWIN_PRINT = argument_prefix + "\targuments = {\n@ARGUMENTS@\n\t}\n" + argument_suffixprefix, _, environment = DARWIN_PRINT.partition("\tenvironment = {\n")_, _, suffix = environment.partition("\n\t}\n")DARWIN_PRINT = ( (prefix + "\tenvironment = {\n@ENV@\n\t}\n" + suffix) .replace("state = not running", "state = @STATE@") .replace("runs = 1", "runs = @RUNS@") .replace("\tlast exit code = 0", "@EXIT@"))
def darwin_daemon() -> None: label = service_name.removesuffix(".plist") loaded = root / "daemon-launchd-loaded.plist" path = Path.home() / "Library/LaunchAgents" / (label + ".plist") record = json.loads(state.read_text()) if state.exists() else {} pid = int(record.get("pid", 0)) if pid: try: os.kill(pid, 0) except ProcessLookupError: pid = 0 if command == "print-disabled": if loaded.exists(): label = plistlib.loads(loaded.read_bytes())["Label"] disabled = (root / "launchd-disabled").exists() print("disabled services = {") if disabled: print(f'\t"{label}" => disabled') print("}") return if command == "print": # print-hook.json acts on the Nth print, before or after its reply, so a # test can change state at a chosen observation boundary. count_file = root / "print-count" count = int(count_file.read_text()) + 1 if count_file.exists() else 1 count_file.write_text(str(count)) hook_file = root / "print-hook.json" hook = json.loads(hook_file.read_text()) if hook_file.exists() else {} if hook.get("call") != count: hook = {} for name, content in hook.get("write", {}).items(): Path(name).write_text(content) fault = root / "launchd-print.json" if fault.exists(): reply = json.loads(fault.read_text()) print(reply.get("stdout", ""), end="") print(reply.get("stderr", ""), end="", file=sys.stderr) sys.exit(reply.get("status", 0)) if not loaded.exists() or plistlib.loads(loaded.read_bytes())["Label"] != label: print( f'Could not find service "{label}" in domain for user gui: {os.getuid()}', file=sys.stderr, ) sys.exit(113) data = plistlib.loads(loaded.read_bytes()) environment = data["EnvironmentVariables"] | { "OSLogRateLimit": "64", "XPC_SERVICE_NAME": label, } values = { "@UID@": str(os.getuid()), "@LABEL@": label, "@PATH@": str(path), "@LOG@": str(root / "daemon.log"), "@PROGRAM@": data["ProgramArguments"][0], "@ARGUMENTS@": "\n".join("\t\t" + arg for arg in data["ProgramArguments"]), "@ENV@": "\n".join( f"\t\t{key} => {value}" for key, value in environment.items() ), "@STATE@": "running" if pid else "not running", "@RUNS@": str(record.get("runs", 1)), "@EXIT@": f"\tpid = {pid}" if pid else "\tlast exit code = 0", } # launchd-retry.json replaces the history of a job with no live process. retry = root / "launchd-retry.json" if retry.exists() and not pid: history = json.loads(retry.read_text()) values["@STATE@"] = history["state"] values["@RUNS@"] = str(history["runs"]) values["@EXIT@"] = "\t" + history["history"] output = DARWIN_PRINT for key, value in values.items(): output = output.replace(key, value) print(output, end="") sys.stdout.flush() if hook.get("kill_after_reply") and pid: os.kill(pid, signal.SIGKILL) while True: try: os.kill(pid, 0) except ProcessLookupError: break time.sleep(0.01) return if command == "bootout": if pid: os.kill(pid, signal.SIGTERM) loaded.unlink(missing_ok=True) elif command in {"bootstrap", "kickstart"}: if "-k" in args: sys.exit("destructive kickstart forbidden") if command == "bootstrap": loaded.write_bytes(Path(args[2]).read_bytes()) if not pid: data = plistlib.loads(loaded.read_bytes()) with (root / "daemon.log").open("ab") as log: child = subprocess.Popen( data["ProgramArguments"], env=os.environ | data["EnvironmentVariables"], stdout=log, stderr=log, start_new_session=True, ) state.write_text( json.dumps({"pid": child.pid, "runs": int(record.get("runs", 0)) + 1}) ) else: sys.exit(f"unexpected launchctl mutation: {args}") (root / (command + "-submitted")).touch() gate = root / (command + "-reply-gate") if gate.exists(): with gate.open() as stream: stream.read() if (root / ("fail-after-" + command)).exists(): sys.exit("mutation submitted but reply failed")
if role == "daemon" and command in { "print", "print-disabled", "bootstrap", "kickstart", "bootout",}: darwin_daemon() sys.exit(0)
if role == "daemon" or command == "daemon-reload": import hashlib
default_name = ( "systems.albedo.daemon-" + hashlib.sha256(str(root).encode()).hexdigest()[:16] + ".service" ) name = default_name if command == "daemon-reload" else service_name registration_name = root / "daemon-unit-name" registered_name = ( registration_name.read_text() if registration_name.exists() else default_name ) path = ( Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "systemd/user" / name ) loaded = root / "daemon-unit-loaded" enabled = root / "daemon-unit-enabled" daemon_state = root / "daemon-service-stub.json" record = json.loads(daemon_state.read_text()) if daemon_state.exists() else {}
def live(pid): if not pid: return False try: if Path(f"/proc/{pid}/stat").read_text().split(") ", 1)[1].startswith("Z"): return False except FileNotFoundError: pass try: os.kill(pid, 0) return True except ProcessLookupError: return False
if command == "daemon-reload": if path.exists(): loaded.write_text(path.read_text()) else: loaded.unlink(missing_ok=True) fault = root / "reload-fault.json" if fault.exists(): options = json.loads(fault.read_text()) fault.unlink() if options.get("external_edit"): with path.open("a") as edited: edited.write("# external edit\n") if options.get("companion"): path.with_name("albedo.service").write_text( "[Unit]\nDescription=another registration\n" ) if options.get("manager_unavailable"): (root / "service-stub-fail").touch() sys.exit("reload reply failed") sys.exit(0) if command == "show": count_file = root / "show-count" count = int(count_file.read_text()) + 1 if count_file.exists() else 1 count_file.write_text(str(count)) data = loaded.read_text() if loaded.exists() and name == registered_name else "" pid = ( record.get("pid", 0) if name == registered_name and live(record.get("pid")) else 0 ) values = { "LoadState": "loaded" if data else "not-found", "ActiveState": "active" if pid else "inactive", "SubState": "running" if pid else "dead", "MainPID": str(pid), "Job": "", "FragmentPath": str(path) if data else "", "UnitFileState": "enabled" if enabled.exists() else "disabled", "InvocationID": record.get("invocation", "") if pid else "", "NeedDaemonReload": "yes" if path.exists() and path.read_text() != data else "no", "Result": "success", "NRestarts": "0", "ExecMainStatus": "0", } if data: argv = shlex.split( next( line[10:] for line in data.splitlines() if line.startswith("ExecStart=") ) ) argv[0] = argv[0].removeprefix(":") argv = [arg.replace("%%", "%") for arg in argv] env = [ shlex.split(line[12:])[0].replace("%%", "%") for line in data.splitlines() if line.startswith("Environment=") ] values.update( { "Type": "exec", "ExitType": "main", "RemainAfterExit": "no", "DropInPaths": "", "TriggeredBy": "", "ExecCondition": "", "ExecStartPre": "", "ExecStartPost": "", "ExecStop": "", "ExecStopPost": "", "EnvironmentFiles": "", "KillMode": "process", "Restart": "on-failure", "RestartPreventExitStatus": "75", "RestartForceExitStatus": "", "KillSignal": "15", "SendSIGHUP": "no", "SendSIGKILL": "yes", "FinalKillSignal": "9", "TimeoutStopUSec": "45s", "TimeoutStopFailureMode": "terminate", "RestartUSec": "3s", "StartLimitIntervalUSec": "1min", "StartLimitBurst": "5", "StandardOutput": "append", "StandardError": "append", "ExecStart": "{ path=" + argv[0] + " ; argv[]=" + " ".join(argv) + " ; ignore_errors=no ; }", "Environment": " ".join(json.dumps(entry) for entry in env), } ) override = root / "daemon-properties.json" if override.exists() and name == registered_name: values.update(json.loads(override.read_text())) if not pid and record and (root / "replacement-on-exit").exists(): values["InvocationID"] = "replacement-invocation" for key, value in values.items(): print(key + "=" + value) sys.stdout.flush() sys.exit(0) if command in {"enable", "disable", "reset-failed"}: if command == "reset-failed": (root / "daemon-properties.json").unlink(missing_ok=True) if command == "enable": enabled.touch() elif command == "disable": enabled.unlink(missing_ok=True) if (root / ("fail-after-" + command)).exists(): sys.exit("command partially applied") sys.exit(0) if command == "start": if not live(record.get("pid")): data = loaded.read_text() argv = shlex.split( next( line[10:] for line in data.splitlines() if line.startswith("ExecStart=") ) ) argv[0] = argv[0].removeprefix(":") argv = [arg.replace("%%", "%") for arg in argv] env = dict(os.environ) for line in data.splitlines(): if line.startswith("Environment="): key, value = shlex.split(line[12:])[0].split("=", 1) env[key] = value.replace("%%", "%") with (root / "daemon.log").open("ab") as log: child = subprocess.Popen( argv, env=env, stdout=log, stderr=log, start_new_session=True ) daemon_state.write_text( json.dumps( {"pid": child.pid, "invocation": str(child.pid), "path": str(path)} ) ) gate = root / "start-reply-gate" if gate.exists(): (root / "start-submitted").touch() with gate.open() as stream: stream.read() if (root / "fail-after-start").exists(): sys.exit("start submitted but reply failed") sys.exit(0) if command == "stop": if live(record.get("pid")): os.kill(record["pid"], signal.SIGTERM) sys.exit(0)
record = json.loads(state.read_text()) if state.exists() else {}command = args[0]if command == "print": sys.exit(0 if record else 113)if command in {"stop", "bootout"}: if record: os.kill(record["pid"], signal.SIGTERM) for _ in range(300): if not (root / (role + ".json")).exists(): break time.sleep(0.02) state.unlink() sys.exit(0)if command in {"disable", "daemon-reload"}: sys.exit(0)if command in {"start", "kickstart"} and record: sys.exit(0)if command == "bootstrap": path = Path(args[2])else: name = args[-1] if sys.platform == "darwin": path = ( Path.home() / "Library" / "LaunchAgents" / (name.split("/")[-1] + ".plist") ) else: path = ( Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "systemd" / "user" / name )if path.suffix == ".plist": data = plistlib.loads(path.read_bytes()) argv = data["ProgramArguments"] env = os.environ | data["EnvironmentVariables"]else: lines = path.read_text().splitlines() argv = shlex.split( next( line.removeprefix("ExecStart=") for line in lines if line.startswith("ExecStart=") ) ) env = dict(os.environ) for line in lines: if line.startswith("Environment="): key, value = shlex.split(line.removeprefix("Environment="))[0].split("=", 1) env[key] = value.replace("%%", "%") argv = [arg.replace("%%", "%") for arg in argv]with (root / (role + ".log")).open("ab") as log: process = subprocess.Popen( argv, env=env, stdout=log, stderr=log, start_new_session=True )state.write_text(json.dumps({"pid": process.pid, "path": str(path)}))