"""Operator commands. Each is one command. python ops.py kill AGENT|global cancel its background job, set the kill flag, revoke the credential(s) python ops.py revoke AGENT credential only python ops.py revoke-tool TOOL disable a tool for every agent, no deploy python ops.py snapshot | restore NAME""" import sys, json, time, shutil, hashlib, pathlib, os, signal, urllib.request import killswitch HERE = pathlib.Path(__file__).parent def jw(n, o): t = HERE / (n + ".tmp"); t.write_text(json.dumps(o)); t.replace(HERE / n) def revoke(agent): c = json.loads((HERE / "creds.json").read_text()) for k, v in c.items(): if agent in ("global", v["agent"]): v["revoked"] = True jw("creds.json", c) def cancel_jobs(agent): creds = json.loads((HERE / "creds.json").read_text()) tok = next((k for k, v in creds.items() if v["agent"] == agent), next(iter(creds))) req = urllib.request.Request("http://127.0.0.1:29200/job/cancel", method="POST", data=json.dumps({"agent": None if agent == "global" else agent}).encode(), headers={"Authorization": f"Bearer {tok}"}) urllib.request.urlopen(req) # must run before the credential is revoked def sha(p): return hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest() if __name__ == "__main__": cmd = sys.argv[1] if cmd == "kill": who = sys.argv[2]; cancel_jobs(who) killswitch.set_state(who, "kill", os.environ.get("USER", "oncall")); revoke(who) elif cmd == "revoke": revoke(sys.argv[2]) elif cmd == "revoke-tool": t = json.loads((HERE / "tools.json").read_text()); t[sys.argv[2]]["enabled"] = False; jw("tools.json", t) elif cmd == "snapshot": name = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + f"-{int(time.time()*1000)%1000:03d}" d = HERE / "snapshots" / name; d.mkdir(parents=True) for f in ("memory.json", "config.json"): shutil.copy(HERE / f, d / f) (d / "MANIFEST.json").write_text(json.dumps({"memory.json": sha(d / "memory.json"), "config.json": sha(d / "config.json")})); print(name) elif cmd == "restore": d = HERE / "snapshots" / sys.argv[2]; man = json.loads((d / "MANIFEST.json").read_text()) for f, h in man.items(): if sha(d / f) != h: sys.exit(f"snapshot {f} fails its hash; refusing to restore") for f in man: shutil.copy(d / f, HERE / f) print("restored", sys.argv[2])