|
| 1 | +from enum import IntEnum |
| 2 | +from logging import Logger |
| 3 | +from multiprocessing.connection import Connection |
| 4 | +from select import select |
| 5 | +from signal import signal, SIGINT, SIGTERM |
| 6 | +from time import sleep |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +from psycopg2 import connect, extensions, InterfaceError |
| 10 | + |
| 11 | + |
| 12 | +CASBIN_CHANNEL_SELECT_TIMEOUT = 1 # seconds |
| 13 | + |
| 14 | + |
| 15 | +def casbin_channel_subscription( |
| 16 | + process_conn: Connection, |
| 17 | + logger: Logger, |
| 18 | + host: str, |
| 19 | + user: str, |
| 20 | + password: str, |
| 21 | + channel_name: str, |
| 22 | + port: int = 5432, |
| 23 | + dbname: str = "postgres", |
| 24 | + delay: int = 2, |
| 25 | + sslmode: Optional[str] = None, |
| 26 | + sslrootcert: Optional[str] = None, |
| 27 | + sslcert: Optional[str] = None, |
| 28 | + sslkey: Optional[str] = None, |
| 29 | +): |
| 30 | + # delay connecting to postgresql (postgresql connection failure) |
| 31 | + sleep(delay) |
| 32 | + db_connection = connect( |
| 33 | + host=host, |
| 34 | + port=port, |
| 35 | + user=user, |
| 36 | + password=password, |
| 37 | + dbname=dbname, |
| 38 | + sslmode=sslmode, |
| 39 | + sslrootcert=sslrootcert, |
| 40 | + sslcert=sslcert, |
| 41 | + sslkey=sslkey, |
| 42 | + ) |
| 43 | + # Can only receive notifications when not in transaction, set this for easier usage |
| 44 | + db_connection.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) |
| 45 | + db_cursor = db_connection.cursor() |
| 46 | + context_manager = _ConnectionManager(db_connection, db_cursor) |
| 47 | + |
| 48 | + with context_manager: |
| 49 | + db_cursor.execute(f"LISTEN {channel_name};") |
| 50 | + logger.debug("Waiting for casbin policy update") |
| 51 | + process_conn.send(_ChannelSubscriptionMessage.IS_READY) |
| 52 | + |
| 53 | + while not db_cursor.closed: |
| 54 | + try: |
| 55 | + select_result = select( |
| 56 | + [db_connection], |
| 57 | + [], |
| 58 | + [], |
| 59 | + CASBIN_CHANNEL_SELECT_TIMEOUT, |
| 60 | + ) |
| 61 | + if select_result != ([], [], []): |
| 62 | + logger.debug("Casbin policy update identified") |
| 63 | + db_connection.poll() |
| 64 | + while db_connection.notifies: |
| 65 | + notify = db_connection.notifies.pop(0) |
| 66 | + logger.debug(f"Notify: {notify.payload}") |
| 67 | + process_conn.send(_ChannelSubscriptionMessage.RECEIVED_UPDATE) |
| 68 | + except (InterfaceError, OSError) as e: |
| 69 | + # Log an exception if these errors occurred without the context beeing closed |
| 70 | + if not context_manager.connections_were_closed: |
| 71 | + logger.critical(e, exc_info=True) |
| 72 | + break |
| 73 | + |
| 74 | + |
| 75 | +class _ChannelSubscriptionMessage(IntEnum): |
| 76 | + IS_READY = 1 |
| 77 | + RECEIVED_UPDATE = 2 |
| 78 | + |
| 79 | + |
| 80 | +class _ConnectionManager: |
| 81 | + """ |
| 82 | + You can not use 'with' and a connection / cursor directly in this setup. |
| 83 | + For more details see this issue: https://github.com/psycopg/psycopg2/issues/941#issuecomment-864025101. |
| 84 | + As a workaround this connection manager / context manager class is used, that also handles SIGINT and SIGTERM and |
| 85 | + closes the database connection. |
| 86 | + """ |
| 87 | + |
| 88 | + def __init__(self, connection, cursor) -> None: |
| 89 | + self.connection = connection |
| 90 | + self.cursor = cursor |
| 91 | + self.connections_were_closed = False |
| 92 | + |
| 93 | + def __enter__(self): |
| 94 | + signal(SIGINT, self._close_connections) |
| 95 | + signal(SIGTERM, self._close_connections) |
| 96 | + return self |
| 97 | + |
| 98 | + def _close_connections(self, *_): |
| 99 | + if self.cursor is not None: |
| 100 | + self.cursor.close() |
| 101 | + self.cursor = None |
| 102 | + if self.connection is not None: |
| 103 | + self.connection.close() |
| 104 | + self.connection = None |
| 105 | + self.connections_were_closed = True |
| 106 | + |
| 107 | + def __exit__(self, *_): |
| 108 | + self._close_connections() |
0 commit comments