|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import importlib.util |
| 4 | +import sys |
| 5 | +import typing |
| 6 | +import warnings |
| 7 | +from pathlib import Path |
| 8 | +from socket import AF_UNIX, SOCK_STREAM, socket |
| 9 | + |
| 10 | +if sys.version_info < (3, 8): # pragma: no-cover-if-py-gte-38 |
| 11 | + from typing_extensions import Protocol |
| 12 | +else: # pragma: no-cover-if-py-lt-38 |
| 13 | + from typing import Protocol |
| 14 | + |
| 15 | +if typing.TYPE_CHECKING: |
| 16 | + from typing import Type |
| 17 | + |
| 18 | + |
| 19 | +class Inhibitor(Protocol): |
| 20 | + """The Inhibitor protocol. An inhibitor module should provide a class |
| 21 | + called Inhibitor which implements this protocol.""" |
| 22 | + |
| 23 | + def start(self, *args) -> None: ... |
| 24 | + def stop(self) -> None: ... |
| 25 | + |
| 26 | + |
| 27 | +CLIENT_CONNECTION_TIMEOUT = 60 |
| 28 | +"""Time to wait (seconds) for the client to connect to the server.""" |
| 29 | +CLIENT_MESSAGE_TIMEOUT = 1 |
| 30 | +"""Time to wait (seconds) for each message from the client.""" |
| 31 | + |
| 32 | + |
| 33 | +class InhibitorServer: |
| 34 | + """A very simple class for inhibiting suspend/idle. |
| 35 | +
|
| 36 | + Communicates with a main process using a Unix domain socket. |
| 37 | +
|
| 38 | + What happens when run() is called: |
| 39 | + 1. When the process starts, inhibit() is called. If it succeeds, this |
| 40 | + process sends "INHIBIT_OK". If it fails, this process sends |
| 41 | + "INHIBIT_ERROR:{errortext}" and exits. |
| 42 | + 2. This process waits indefinitely for a "QUIT" message. |
| 43 | + 3. When "QUIT" (or empty string) is received, uninhibit() is called. If it |
| 44 | + succeeds, this process sends "UNINHIBIT_OK". If it fails, this process |
| 45 | + sends "UNINHIBIT_ERROR". Then, this process exits. |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__(self): |
| 49 | + self._inhibitor: Inhibitor | None = None |
| 50 | + |
| 51 | + def run(self, socket_path: str, inhibitor_module: str, *inhibit_args) -> None: |
| 52 | + """Inhibit the system using inhibitor_module and wait for a quit |
| 53 | + message at socket_path. |
| 54 | +
|
| 55 | + Parameters |
| 56 | + ---------- |
| 57 | + socket_path : str |
| 58 | + The path to the Unix domain socket which is used for communication. |
| 59 | + inhibitor_module : str |
| 60 | + The python module that contains the Inhibitor class |
| 61 | + inhibit_args: |
| 62 | + Any arguments to the Inhibitor.start() method. |
| 63 | + """ |
| 64 | + server_socket = socket(AF_UNIX, SOCK_STREAM) |
| 65 | + Path(socket_path).expanduser().unlink(missing_ok=True) |
| 66 | + server_socket.bind(socket_path) |
| 67 | + |
| 68 | + try: |
| 69 | + self._run(server_socket, inhibitor_module, *inhibit_args) |
| 70 | + finally: |
| 71 | + server_socket.close() |
| 72 | + |
| 73 | + def _run(self, server_socket: socket, inhibitor_module: str, *inhibit_args) -> None: |
| 74 | + server_socket.listen(1) # Only allow 1 connection at a time |
| 75 | + client_socket = self._get_client_socket(server_socket) |
| 76 | + client_socket.settimeout(CLIENT_MESSAGE_TIMEOUT) |
| 77 | + |
| 78 | + try: |
| 79 | + self.inhibit(inhibitor_module, *inhibit_args) |
| 80 | + self.send_message(client_socket, "INHIBIT_OK") |
| 81 | + except Exception as error: |
| 82 | + self.send_message(client_socket, f"INHIBIT_ERROR:{error}") |
| 83 | + sys.exit(0) |
| 84 | + |
| 85 | + while True: |
| 86 | + # Called every `CLIENT_MESSAGE_TIMEOUT` seconds. |
| 87 | + should_quit = self.check_for_quit_message(client_socket) |
| 88 | + if should_quit: |
| 89 | + break |
| 90 | + |
| 91 | + try: |
| 92 | + self.uninhibit() |
| 93 | + self.send_message(client_socket, "UNINHIBIT_OK") |
| 94 | + except Exception as error: |
| 95 | + self.send_message(client_socket, f"UNINHIBIT_ERROR:{error}") |
| 96 | + sys.exit(0) |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def _get_client_socket(server_socket: socket) -> socket: |
| 100 | + server_socket.settimeout(CLIENT_CONNECTION_TIMEOUT) |
| 101 | + |
| 102 | + try: |
| 103 | + client_socket, _ = server_socket.accept() |
| 104 | + except TimeoutError as e: |
| 105 | + raise TimeoutError( |
| 106 | + f"Client did not connect within {CLIENT_CONNECTION_TIMEOUT} seconds." |
| 107 | + ) from e |
| 108 | + except KeyboardInterrupt: |
| 109 | + print("Interrupted manually. Exiting.") |
| 110 | + sys.exit(0) |
| 111 | + |
| 112 | + return client_socket |
| 113 | + |
| 114 | + def inhibit(self, inhibitor_module: str, *inhibit_args) -> None: |
| 115 | + """Inhibit using the Inhibitor class in the given `inhibitor_module`. |
| 116 | + In case the operation fails, raises a RuntimeError.""" |
| 117 | + inhibitor_class = self.get_inhibitor_class(inhibitor_module) |
| 118 | + self._inhibitor = inhibitor_class() |
| 119 | + self._inhibitor.start(*inhibit_args) |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def get_inhibitor_class(inhibitor_module_path: str) -> Type[Inhibitor]: |
| 123 | + try: |
| 124 | + module_name = "__wakepy_inhibitor" |
| 125 | + spec = importlib.util.spec_from_file_location( |
| 126 | + module_name, inhibitor_module_path |
| 127 | + ) |
| 128 | + module = importlib.util.module_from_spec(spec) |
| 129 | + sys.modules[module_name] = module |
| 130 | + spec.loader.exec_module(module) |
| 131 | + except ImportError as e: |
| 132 | + raise ImportError( |
| 133 | + f"{e} | Used python interpreter: {sys.executable}." |
| 134 | + ) from e |
| 135 | + return module.Inhibitor |
| 136 | + |
| 137 | + def uninhibit(self) -> None: |
| 138 | + """Uninhibit what was inhibited. In case the operation fails, raises a |
| 139 | + RuntimeError.""" |
| 140 | + if self._inhibitor: |
| 141 | + self._inhibitor.stop() |
| 142 | + self._inhibitor = None |
| 143 | + else: |
| 144 | + warnings.warn("Called uninhibit before inhibit -> doing nothing.") |
| 145 | + |
| 146 | + def send_message(self, client_socket: socket, message: str) -> None: |
| 147 | + client_socket.sendall(message.encode()) |
| 148 | + |
| 149 | + def check_for_quit_message(self, sock: socket) -> bool: |
| 150 | + # waits until the socket gets a message |
| 151 | + try: |
| 152 | + request = sock.recv(1024).decode() |
| 153 | + except TimeoutError: |
| 154 | + return False |
| 155 | + print(f"Received request: {request}") |
| 156 | + # if the client disconnects, empty string is returned. This will make |
| 157 | + # sure that the server process quits automatically when it's not needed |
| 158 | + # anymore. |
| 159 | + return request == "QUIT" or request == "" |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + # This is the entry point for the inhibitor server, and it's called |
| 164 | + # automatically when using the start_inhibit_server() |
| 165 | + |
| 166 | + if len(sys.argv) < 3: |
| 167 | + print( |
| 168 | + f"Usage: python {__file__} <socket_path> <inhibitor_module> " |
| 169 | + "[inhibit_args...]" |
| 170 | + ) |
| 171 | + sys.exit(1) |
| 172 | + |
| 173 | + # Get the socket path from the command-line arguments |
| 174 | + InhibitorServer().run( |
| 175 | + socket_path=sys.argv[1], inhibitor_module=sys.argv[2], *sys.argv[3:] |
| 176 | + ) |
0 commit comments