diff --git a/api/remote_ispyb_connector.py b/api/remote_ispyb_connector.py index f80be60f..56fce7dc 100644 --- a/api/remote_ispyb_connector.py +++ b/api/remote_ispyb_connector.py @@ -12,6 +12,8 @@ ISPyBRetrieveFailed, ) +logger: logging.Logger = logging.getLogger(__name__) + class SSHConnector(Connector): def __init__( @@ -34,6 +36,7 @@ def __init__( self.conn_inactivity = conn_inactivity self.lock = threading.Lock() + self.conn = None self.server = None self.last_activity_ts = None @@ -49,6 +52,12 @@ def __init__( 'db_name': db, } self.remote_connect(**creds) + logger.debug( + "Started host=%s username=%s local_bind_port=%s", + ssh_host, + ssh_user, + self.server.local_bind_port, + ) else: self.connect( @@ -59,6 +68,7 @@ def __init__( port=port, conn_inactivity=conn_inactivity, ) + logger.debug("Started host=%s user=%s port=%s", host, user, port) def remote_connect( self, ssh_host, ssh_user, ssh_pass, db_host, db_port, db_user, db_pass, db_name @@ -125,3 +135,11 @@ def call_sp_retrieve(self, procname, args): if result == []: raise ISPyBNoResultException return result + + def stop(self): + if self.server is not None: + self.server.stop() + self.server = None + self.conn = None + self.last_activity_ts = None + logger.debug("Server stopped") diff --git a/api/security.py b/api/security.py index 888aa61e..fdd8e184 100644 --- a/api/security.py +++ b/api/security.py @@ -92,6 +92,7 @@ def get_conn() -> Optional[Connector]: # Assume the credentials are invalid if there is no host. # If a host is not defined other properties are useless. if not credentials["host"]: + logger.debug("No ISPyB host - cannot return a connector") return None conn: Optional[Connector] = None @@ -115,6 +116,21 @@ def get_configured_connector() -> Optional[Union[Connector, SSHConnector]]: return None +def ping_configured_connector() -> bool: + """Pings the connector. If a connection can be obtained it is immediately closed. + The ping simply provides a way to check the credentials are valid and + a connection can be made. + """ + conn: Optional[Union[Connector, SSHConnector]] = None + if connector == 'ispyb': + conn = get_conn() + elif connector == 'ssh_ispyb': + conn = get_remote_conn() + if conn is not None: + conn.stop() + return conn is not None + + class ISpyBSafeQuerySet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): """ diff --git a/viewer/services.py b/viewer/services.py index 69533ca9..a203bfc3 100644 --- a/viewer/services.py +++ b/viewer/services.py @@ -9,7 +9,7 @@ from frag.utils.network_utils import get_driver from pydiscourse import DiscourseClient -from api.security import get_configured_connector +from api.security import ping_configured_connector from viewer.squonk2_agent import get_squonk2_agent logger = logging.getLogger(__name__) @@ -156,7 +156,7 @@ def ispyb(func_id, name, ispyb_host=None) -> bool: del func_id, name, ispyb_host logger.debug("+ ispyb") - return get_configured_connector() != None + return ping_configured_connector() @service_query