Files

44 lines
1.5 KiB
Python

"""Watchdog: restart the EduForge bot if its poller is dead. Run via cron (no_agent)."""
import os
import sys
import subprocess
import psutil
BASE = r"C:/Users/User/tmp/eduforge_bot"
PY = r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe"
def alive():
for p in psutil.process_iter(["pid", "name", "cmdline", "cwd"]):
try:
cl = p.info["cmdline"] or []
cwd = (p.info["cwd"] or "").lower().replace("\\", "/")
if (p.info["name"] or "").lower() == "python.exe" \
and cwd == BASE.lower().replace("\\", "/") \
and any(str(a).endswith("bot.py") for a in cl) \
and "-c" not in cl:
est = sum(1 for c in p.net_connections(kind="inet") if c.status == "ESTABLISHED")
if est > 0:
return True
except Exception:
pass
return False
def main():
if alive():
return # silent when healthy (watchdog pattern: empty stdout = no delivery)
env = dict(os.environ)
env.pop("PYTHONPATH", None)
env["PYTHONIOENCODING"] = "utf-8"
env["PYTHONUNBUFFERED"] = "1"
log = open(os.path.join(BASE, "bot.log"), "a", encoding="utf-8")
DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
subprocess.Popen([PY, "-u", "bot.py"], cwd=BASE, env=env,
stdout=log, stderr=log, stdin=subprocess.DEVNULL,
creationflags=DETACHED)
print("restarted bot")
if __name__ == "__main__":
main()