From 7af07b3e114220e1c8aa45df081f5ed3119feacf Mon Sep 17 00:00:00 2001 From: Pablo Martin Date: Thu, 21 Jul 2022 18:26:23 +0200 Subject: [PATCH] Created singleton for opening and closing SSH tunnel. --- connections.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/connections.py b/connections.py index 8d7e34c..e20208a 100644 --- a/connections.py +++ b/connections.py @@ -4,6 +4,39 @@ import mysql.connector import trino.dbapi from trino.auth import BasicAuthentication from trino.dbapi import connect +from sshtunnel import SSHTunnelForwarder + + +def singleton(class_): + instances = {} + + def getinstance(*args, **kwargs): + if class_ not in instances: + instances[class_] = class_(*args, **kwargs) + return instances[class_] + + return getinstance + + +@singleton +class MySSHTunnel: + def __init__( + self, ssh_host, ssh_port, ssh_username, ssh_pkey, remote_host, remote_port + ): + + self.tunnel = SSHTunnelForwarder( + ssh_host=(ssh_host, ssh_port), + ssh_username=ssh_username, + ssh_pkey=ssh_pkey, + remote_bind_address=(remote_host, remote_port), + local_bind_address=("127.0.0.1", remote_port), + ) + + def start(self): + self.tunnel.start() + + def stop(self): + self.tunnel.stop() def get_connection(connection_config: dict) -> Union[trino.dbapi.Connection]: