idle_watch.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """One idle check for a Bot Desktop screen, run by the screen's own launcher.
  2. The screen outlives the gateway that started it on purpose (a restarted gateway re-attaches to it), so the
  3. gateway's display watcher cannot be the only thing that ever stops it: when no gateway comes back, Xvnc +
  4. Xfce and any browser left open run until reboot. ``launcher.sh`` therefore runs this module (through the
  5. install's stable command) in a loop of its own. Each run applies :func:`runtime.stop_if_idle` (the same
  6. ``bot_desktop.idle_stop_minutes`` window and the same human-lease rule as the gateway's watcher) and prints
  7. how long the launcher should sleep before the next run, so no interpreter stays resident between checks.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import math
  12. import os
  13. import sys
  14. from typing import Optional
  15. from tools.bot_desktop import runtime
  16. logger = logging.getLogger(__name__)
  17. _MIN_DELAY_S = 30.0 # the gateway watcher's cadence; a window shorter than that is checked at its own length
  18. def next_check_in(limit: float, idle: Optional[float]) -> int:
  19. """Whole seconds until the screen could next be due: when the window runs out at the current idle age,
  20. or a full window later while something (a human holding it) keeps it past that. With the auto-stop off
  21. (``limit <= 0``) the setting is re-read every default window."""
  22. if limit <= 0:
  23. return runtime.DEFAULT_IDLE_STOP_MINUTES * 60
  24. idle = idle or 0.0
  25. return math.ceil(max(min(_MIN_DELAY_S, limit), limit - idle if idle < limit else limit))
  26. def _own_launcher(argv: list[str]) -> Optional[tuple[int, float]]:
  27. """``(pid, create_time)`` of the launcher that ran this check (its pid is the one argument), so the
  28. check stops only that screen and never a replacement started while it waited on ``start.lock``. A
  29. launcher already gone gets an identity nothing matches."""
  30. pid_s = argv[0] if argv else ""
  31. if not pid_s.isdigit():
  32. return None
  33. born = runtime._create_time(int(pid_s))
  34. return int(pid_s), born if born is not None else -1.0
  35. def main() -> None:
  36. logging.basicConfig(level=logging.INFO, format="%(asctime)s idle-watch %(message)s") # stderr = launcher.log
  37. if runtime.stop_if_idle(launcher=_own_launcher(sys.argv[1:])):
  38. return
  39. delay = next_check_in(runtime.idle_stop_seconds(), runtime.idle_seconds())
  40. logger.info("screen kept; next idle check in %ds", delay)
  41. print(delay)
  42. if __name__ == "__main__":
  43. # stop() kills the launcher's process group, which this check was started in; in a session of its own it
  44. # survives that kill to finish the stop (SIGKILL stragglers, drop the runtime files), then exits. A process
  45. # that already leads its group (run by hand from a shell) cannot setsid and is not in the launcher's group.
  46. if os.getpgrp() != os.getpid(): # windows-footgun: ok — Linux-only (launcher.sh)
  47. os.setsid() # windows-footgun: ok — Linux-only (launcher.sh) detached-spawn: ok — short-lived, outlives the group kill it performs
  48. main()