:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): retry a failed SSH tunnel connect (#111536)
Tom Owers023b7b7f74af
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex 584a5938e0ae..afc94a657964 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py@@ -4,13 +4,14 @@ import socketimport ipaddressimport dataclassesfrom collections.abc import Callable, Generator, Sequence-from contextlib import _GeneratorContextManager, contextmanager+from contextlib import ExitStack, _GeneratorContextManager, contextmanagerfrom typing import Any, Generic, TypeVarfrom django.conf import settingsfrom django.db import OperationalError, close_old_connectionsimport structlog+from sshtunnel import BaseSSHTunnelForwarderError, SSHTunnelForwarderfrom posthog.cloud_utils import is_cloudfrom posthog.dataclasses import frozen@@ -580,6 +581,79 @@ def _check_direct_host(config, team_id: int | None) -> None:_checked_connect_host(config.host, team_id, DATABASE_HOST_NOT_ALLOWED_ERROR)+# sshtunnel reports every failure to reach the gateway with the same wording. `_create_tunnels`+# swallows the DNS error, the refused socket and the rejected credentials alike, and then `start`+# raises a fixed "Could not establish session to SSH gateway". `Any_Source_Errors` classifies that+# message as non-retryable, so a single failed connect disables every table under the source, and a+# bastion that was restarting costs a customer their whole sync. Retry the connect before giving up.+# The budget is bounded, so a wrong credential or a host that is really gone reaches the same+# classification it reaches today, about 14 seconds later.+_SSH_TUNNEL_CONNECT_BACKOFF_SECONDS: tuple[float, ...] = (2.0, 4.0, 8.0)+++def _release_failed_forwarder(forwarder: SSHTunnelForwarder) -> None:+ """Release the sockets and threads a failed `start` left behind.++ `start` raises after `_create_tunnels` has already built the local forward servers, and a+ forwarder cannot be started a second time, so every attempt needs a new forwarder and the+ failed one has to let go of its resources first.+ """+ if forwarder.is_active:+ try:+ forwarder.stop(force=True)+ except Exception as e:+ logger.debug("data_imports.ssh_tunnel_cleanup_failed", error=str(e)[:200])+ return++ # sshtunnel creates the local servers even when gateway authentication fails, but it raises+ # before starting their serve_forever threads. Its stop() calls shutdown() on those servers,+ # which waits forever for an unstarted thread. Close their sockets and transport directly.+ for server in forwarder._server_list:+ try:+ server.server_close()+ except Exception as e:+ logger.debug("data_imports.ssh_tunnel_cleanup_failed", error=str(e)[:200])+ forwarder._server_list = []+ forwarder.tunnel_is_up = {}++ transport = getattr(forwarder, "_transport", None)+ if transport is not None:+ for method in (transport.close, transport.stop_thread):+ try:+ method()+ except Exception as e:+ logger.debug("data_imports.ssh_tunnel_cleanup_failed", error=str(e)[:200])+++@contextmanager+def _connected_ssh_tunnel(ssh_tunnel: SSHTunnel, config, *, ssh_host: str) -> Generator[SSHTunnelForwarder]:+ """Yield a started forwarder, retrying a failed connect to the gateway.++ The retry covers the connect only. Once the tunnel is up, the caller's body runs inside the+ forwarder's own context, so a tunnel that drops part way through a sync still propagates on its+ first occurrence instead of restarting the sync.+ """+ attempts = len(_SSH_TUNNEL_CONNECT_BACKOFF_SECONDS) + 1+ with ExitStack() as stack:+ for attempt in range(attempts):+ forwarder = ssh_tunnel.get_tunnel(config.host, config.port, ssh_host=ssh_host)+ try:+ tunnel = stack.enter_context(forwarder)+ except BaseSSHTunnelForwarderError:+ _release_failed_forwarder(forwarder)+ if attempt == attempts - 1:+ raise+ logger.warning(+ "data_imports.ssh_tunnel_connect_retry",+ attempt=attempt + 1,+ attempts=attempts,+ )+ time.sleep(_SSH_TUNNEL_CONNECT_BACKOFF_SECONDS[attempt])+ continue+ yield tunnel+ return++@contextmanagerdef open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str, int]]:"""Yield `(host, port)` for a database connection, going through an SSH tunnel if configured."""@@ -588,9 +662,7 @@ def open_ssh_tunnel(config, team_id: int | None = None) -> Generator[tuple[str,if ssh_config is not None:ssh_tunnel = SSHTunnel.from_config(ssh_config)- with ssh_tunnel.get_tunnel(- config.host, config.port, ssh_host=_pinned_ssh_host(ssh_config, team_id)- ) as tunnel:+ with _connected_ssh_tunnel(ssh_tunnel, config, ssh_host=_pinned_ssh_host(ssh_config, team_id)) as tunnel:if tunnel is None:raise Exception("Can't open tunnel to SSH server")@@ -617,8 +689,8 @@ def make_ssh_tunnel_factory(with _logged_connection(config, team_id):# Resolved per reopen, not once when the factory is built, so a long-running# sync that reopens the tunnel re-checks the host each time.- with ssh_tunnel.get_tunnel(- config.host, config.port, ssh_host=_pinned_ssh_host(ssh_config, team_id)+ with _connected_ssh_tunnel(+ ssh_tunnel, config, ssh_host=_pinned_ssh_host(ssh_config, team_id)) as tunnel:if tunnel is None:raise Exception("Can't open tunnel to SSH server")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.pyindex bbbdba9457b0..b303f258bbc6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py@@ -9,6 +9,7 @@ from django.db import OperationalErrorfrom django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.dataclasses import frozenfrom posthog.models.integration import Integration@@ -20,12 +21,14 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ _SSH_TUNNEL_CONNECT_BACKOFF_SECONDS,HostNotAllowedError,OAuthMixin,SSHTunnelMixin,TemporaryHostResolutionError,ValidateDatabaseHostMixin,_is_host_safe,+ _release_failed_forwarder,bracket_host,check_resolved_addresses,make_ssh_tunnel_factory,@@ -512,6 +515,96 @@ class TestSSHTunnelHostIsCheckedAtConnect(SimpleTestCase):mock_ssh.from_config.return_value.get_tunnel.assert_not_called()+class TestSSHTunnelConnectRetry(SimpleTestCase):+ # sshtunnel gives one message to every failed connect, and that message is non-retryable, so+ # before the retry a single blip on a shared bastion disabled every table under the source.+ @staticmethod+ def _forwarder(*, fails: bool):+ forwarder = mock.MagicMock()+ if fails:+ forwarder.is_active = False+ forwarder.failed_server = mock.Mock()+ forwarder._server_list = [forwarder.failed_server]+ forwarder._transport = mock.Mock()+ forwarder.__enter__.side_effect = BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")+ else:+ tunnel = forwarder.__enter__.return_value+ tunnel.local_bind_host, tunnel.local_bind_port = "127.0.0.1", 55555+ return forwarder++ @staticmethod+ def _tunnel_cm(entrypoint: str, config):+ if entrypoint == "open_ssh_tunnel":+ return open_ssh_tunnel(config, 42)+ return make_ssh_tunnel_factory(config, 42)()++ @staticmethod+ def _config():+ return FakeConfig(ssh_tunnel=FakeSSHTunnelConfig(enabled=True, host="0.tcp.ngrok.example"))++ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ def test_tunnel_opens_when_a_later_connect_attempt_succeeds(self, entrypoint: str):+ failed = [self._forwarder(fails=True), self._forwarder(fails=True)]+ with (+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,+ patch(f"{_MIXINS_MODULE}.time.sleep"),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ get_tunnel = mock_ssh.from_config.return_value.get_tunnel+ get_tunnel.side_effect = [*failed, self._forwarder(fails=False)]+ with self._tunnel_cm(entrypoint, self._config()) as (host, port):+ assert (host, port) == ("127.0.0.1", 55555)+ assert get_tunnel.call_count == 3+ # Authentication failures create local servers without starting their serving threads.+ # Closing them directly avoids stop() blocking forever in server.shutdown().+ for forwarder in failed:+ forwarder.stop.assert_not_called()+ forwarder.failed_server.server_close.assert_called_once_with()+ forwarder._transport.close.assert_called_once_with()+ forwarder._transport.stop_thread.assert_called_once_with()++ def test_active_failed_forwarder_uses_normal_stop(self):+ forwarder = mock.MagicMock()+ forwarder.is_active = True++ _release_failed_forwarder(forwarder)++ forwarder.stop.assert_called_once_with(force=True)++ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ def test_connect_failing_every_attempt_still_raises_the_gateway_error(self, entrypoint: str):+ attempts = len(_SSH_TUNNEL_CONNECT_BACKOFF_SECONDS) + 1+ with (+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,+ patch(f"{_MIXINS_MODULE}.time.sleep") as mock_sleep,+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ get_tunnel = mock_ssh.from_config.return_value.get_tunnel+ get_tunnel.side_effect = [self._forwarder(fails=True) for _ in range(attempts)]+ with pytest.raises(BaseSSHTunnelForwarderError, match="Could not establish session to SSH gateway"):+ with self._tunnel_cm(entrypoint, self._config()):+ pass+ # The budget stays bounded, so a credential that is really wrong reaches the same+ # classification it reached before the retry existed.+ assert get_tunnel.call_count == attempts+ assert mock_sleep.call_count == attempts - 1++ @parameterized.expand([("open_ssh_tunnel",), ("factory",)])+ def test_failure_after_the_tunnel_is_up_does_not_reconnect(self, entrypoint: str):+ # Reopening here would restart a sync that had already begun reading rows.+ with (+ patch(f"{_MIXINS_MODULE}.SSHTunnel") as mock_ssh,+ patch(f"{_MIXINS_MODULE}.time.sleep"),+ patch(f"{_MIXINS_MODULE}.logger"),+ ):+ get_tunnel = mock_ssh.from_config.return_value.get_tunnel+ get_tunnel.side_effect = [self._forwarder(fails=False), self._forwarder(fails=False)]+ with pytest.raises(ConnectionRefusedError):+ with self._tunnel_cm(entrypoint, self._config()):+ raise ConnectionRefusedError("dropped mid-sync")+ assert get_tunnel.call_count == 1++class TestOAuthMixinIntegrationFetchResilience(SimpleTestCase):@parameterized.expand([