Client for connecting to gunicorn control socket. Can be used as a context manager: with ControlClient('/path/to/gunicorn.ctl') as client: result = client.send_command('show workers')
| 22 | |
| 23 | |
| 24 | class ControlClient: |
| 25 | """ |
| 26 | Client for connecting to gunicorn control socket. |
| 27 | |
| 28 | Can be used as a context manager: |
| 29 | |
| 30 | with ControlClient('/path/to/gunicorn.ctl') as client: |
| 31 | result = client.send_command('show workers') |
| 32 | """ |
| 33 | |
| 34 | def __init__(self, socket_path: str, timeout: float = 30.0): |
| 35 | """ |
| 36 | Initialize control client. |
| 37 | |
| 38 | Args: |
| 39 | socket_path: Path to the Unix socket |
| 40 | timeout: Socket timeout in seconds (default 30) |
| 41 | """ |
| 42 | self.socket_path = socket_path |
| 43 | self.timeout = timeout |
| 44 | self._sock = None |
| 45 | self._request_id = 0 |
| 46 | |
| 47 | def connect(self): |
| 48 | """ |
| 49 | Connect to control socket. |
| 50 | |
| 51 | Raises: |
| 52 | ControlClientError: If connection fails |
| 53 | """ |
| 54 | if self._sock: |
| 55 | return |
| 56 | |
| 57 | try: |
| 58 | self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 59 | self._sock.settimeout(self.timeout) |
| 60 | self._sock.connect(self.socket_path) |
| 61 | except socket.error as e: |
| 62 | self._sock = None |
| 63 | raise ControlClientError(f"Failed to connect to {self.socket_path}: {e}") |
| 64 | |
| 65 | def close(self): |
| 66 | """Close connection.""" |
| 67 | if self._sock: |
| 68 | try: |
| 69 | self._sock.close() |
| 70 | except Exception: |
| 71 | pass |
| 72 | self._sock = None |
| 73 | |
| 74 | def send_command(self, command: str, args: list = None) -> dict: |
| 75 | """ |
| 76 | Send command and wait for response. |
| 77 | |
| 78 | Args: |
| 79 | command: Command string (e.g., "show workers") |
| 80 | args: Optional additional arguments |
| 81 |
no outgoing calls