diff --git a/kubernetes/stream/stream.py b/kubernetes/stream/stream.py index 6ca5f14e4b..eddcb4188c 100644 --- a/kubernetes/stream/stream.py +++ b/kubernetes/stream/stream.py @@ -28,6 +28,7 @@ def _websocket_request(websocket_request, force_kwargs, api_method, *args, **kwa preload_content = kwargs.pop('_preload_content', True) kwargs['_preload_content'] = False binary = kwargs.pop('binary', False) + ping_interval = kwargs.pop('ping_interval', None) previous_call_api = api_client.call_api # Legacy-compatible generated methods preserve _preload_content=False @@ -41,10 +42,7 @@ def call_api( post_params=None, _request_timeout=None, ): - response = websocket_request( - configuration, - method, - url, + req_kwargs = dict( headers=header_params, body=body, post_params=post_params, @@ -52,6 +50,14 @@ def call_api( _preload_content=preload_content, binary=binary, ) + if ping_interval is not None: + req_kwargs['ping_interval'] = ping_interval + response = websocket_request( + configuration, + method, + url, + **req_kwargs, + ) return SimpleNamespace( response=response, status=response.status diff --git a/kubernetes/stream/ws_client.py b/kubernetes/stream/ws_client.py index eeac7aba73..d9ea147d65 100644 --- a/kubernetes/stream/ws_client.py +++ b/kubernetes/stream/ws_client.py @@ -29,6 +29,7 @@ import yaml from requests.utils import should_bypass_proxies +from kubernetes.utils.keepalive import tcp_keepalive_socket_options STDIN_CHANNEL = 0 STDOUT_CHANNEL = 1 @@ -50,7 +51,7 @@ def getvalue(self): class WSClient: def __init__(self, configuration, url, headers, capture_all, binary=False, - _request_timeout=None): + _request_timeout=None, ping_interval=None): """A websocket client with support for channels. Exec command uses different channels for different streams. for @@ -81,6 +82,29 @@ def __init__(self, configuration, url, headers, capture_all, binary=False, self._connected = True self._returncode = None + self._ping_interval = ping_interval + self._ping_stop_event = threading.Event() + self._ping_thread = None + + if (not isinstance(self._ping_interval, bool) + and isinstance(self._ping_interval, (int, float)) + and self._ping_interval > 0): + self._ping_thread = threading.Thread( + name="Kubernetes WSClient ping worker", + target=self._send_ping_worker + ) + self._ping_thread.daemon = True + self._ping_thread.start() + + def _send_ping_worker(self): + while not self._ping_stop_event.wait(timeout=self._ping_interval): + if not self.is_open() or not self.sock: + break + try: + self.sock.ping() + except Exception: + break + def peek_channel(self, channel, timeout=0): """Peek a channel and return part of the input, empty string otherwise.""" @@ -260,6 +284,8 @@ def update(self, timeout=0): op_code, frame = self.sock.recv_data_frame(True) if op_code == ABNF.OPCODE_CLOSE: self._connected = False + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() return elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT: data = frame.data @@ -301,16 +327,20 @@ def update(self, timeout=0): def run_forever(self, timeout=None): """Wait till connection is closed or timeout reached. Buffer any input received during this time.""" - if timeout: - if isinstance(timeout, tuple) and len(timeout) == 2: - timeout = timeout[1] + try: if timeout: - start = time.time() - while self.is_open() and time.time() - start < timeout: - self.update(timeout=(timeout - time.time() + start)) - return - while self.is_open(): - self.update(timeout=None) + if isinstance(timeout, tuple) and len(timeout) == 2: + timeout = timeout[1] + if timeout: + start = time.time() + while self.is_open() and time.time() - start < timeout: + self.update(timeout=(timeout - time.time() + start)) + return + while self.is_open(): + self.update(timeout=None) + finally: + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() @property def returncode(self): """ @@ -334,6 +364,8 @@ def close(self, **kwargs): close websocket connection. """ self._connected = False + if hasattr(self, '_ping_stop_event') and self._ping_stop_event: + self._ping_stop_event.set() if self.sock: self.sock.close(**kwargs) @@ -618,6 +650,17 @@ def create_websocket(configuration, url, headers=None, _request_timeout=None): websocket.connect(url, **connect_opt) if _request_timeout is not None: websocket.settimeout(read_timeout) + if hasattr(websocket, 'sock') and websocket.sock: + try: + socket_options = getattr(configuration, 'socket_options', None) + if isinstance(socket_options, (list, tuple)): + for opt in socket_options: + websocket.sock.setsockopt(*opt) + elif getattr(configuration, 'keep_alive', False) is True: + for opt in tcp_keepalive_socket_options(): + websocket.sock.setsockopt(*opt) + except (OSError, socket.error, AttributeError): + pass return websocket def websocket_proxycare(connect_opt, configuration, url, headers): @@ -657,9 +700,11 @@ def websocket_call(configuration, _method, url, **kwargs): _preload_content = kwargs.get("_preload_content", True) capture_all = kwargs.get("capture_all", True) binary = kwargs.get('binary', False) + ping_interval = kwargs.get('ping_interval') try: client = WSClient(configuration, url, headers, capture_all, binary=binary, - _request_timeout=_request_timeout) + _request_timeout=_request_timeout, + ping_interval=ping_interval) if not _preload_content: return client client.run_forever(timeout=_request_timeout) diff --git a/kubernetes/stream/ws_client_test.py b/kubernetes/stream/ws_client_test.py index afbe1b0685..9a313babe4 100644 --- a/kubernetes/stream/ws_client_test.py +++ b/kubernetes/stream/ws_client_test.py @@ -27,6 +27,7 @@ import socket import ssl import threading +import time import pytest from kubernetes import stream, client, config import websocket @@ -868,5 +869,186 @@ def test_no_context_when_verify_ssl_is_off(self): self.assertEqual(sslopt['cert_reqs'], ssl.CERT_NONE) +class WSClientPingPongTest(unittest.TestCase): + def setUp(self): + self.config_mock = MagicMock() + self.config_mock.assert_hostname = False + self.config_mock.api_key = {} + self.config_mock.proxy = None + self.config_mock.ssl_ca_cert = None + self.config_mock.cert_file = None + self.config_mock.key_file = None + self.config_mock.verify_ssl = True + self.config_mock.keep_alive = False + self.config_mock.socket_options = None + + def _make_client(self, mock_ws, **kwargs): + with patch.object(ws_client_module, 'create_websocket') as mock_create: + mock_create.return_value = mock_ws + return WSClient(self.config_mock, "wss://test", headers=None, + capture_all=True, **kwargs) + + def test_ping_worker_sends_ping(self): + """Verify background thread sends ping frames at ping_interval.""" + mock_ws = MagicMock() + mock_ws.subprotocol = V5_CHANNEL_PROTOCOL + mock_ws.connected = True + client = self._make_client(mock_ws, ping_interval=0.01) + try: + time.sleep(0.05) + self.assertTrue(mock_ws.ping.called) + finally: + client.close() + client._ping_thread.join(timeout=1) + self.assertFalse(client._ping_thread.is_alive()) + + def test_ping_opt_in_and_invalid_intervals(self): + """Verify app-level pings stay opt-in and skip non-positive or bool values.""" + mock_ws = MagicMock() + mock_ws.connected = True + for interval in (None, 0, -5, True): + client = self._make_client(mock_ws, ping_interval=interval) + try: + self.assertIsNone(client._ping_thread) + finally: + client.close() + + def test_update_responds_to_ping_with_single_pong(self): + """Verify receiving a PING frame responds with exactly one PONG frame.""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + client = self._make_client(ws) + + ping_payload = b'heartbeat-test' + ping_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PING, 0, ping_payload).format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(ping_frame + close_frame) + + with patch.object(ws, 'pong', wraps=ws.pong) as mock_pong: + client.update(timeout=2) + mock_pong.assert_called_once_with(ping_payload) + finally: + server_sock.close() + client_sock.close() + client.close() + + def test_update_handles_pong_frame_without_error(self): + """Verify receiving a PONG frame is tolerated cleanly in update().""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + client = self._make_client(ws) + + pong_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PONG, 0, b'').format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(pong_frame + close_frame) + + client.update(timeout=2) + self.assertFalse(client.is_open()) + finally: + server_sock.close() + client_sock.close() + client.close() + + def test_keep_alive_config_does_not_start_ping_thread(self): + """Verify keep_alive=True only configures TCP keepalive, not app-level pings.""" + self.config_mock.keep_alive = True + mock_ws = MagicMock() + mock_ws.connected = True + client = self._make_client(mock_ws) + try: + self.assertIsNone(client._ping_interval) + self.assertIsNone(client._ping_thread) + finally: + client.close() + + def test_create_websocket_applies_keepalive_socket_options(self): + """Verify create_websocket applies TCP keepalive socket options when keep_alive=True.""" + config = Configuration() + config.keep_alive = True + with patch.object(ws_client_module, 'WebSocket', autospec=True) as mock_ws_cls: + mock_ws = mock_ws_cls.return_value + mock_sock = MagicMock() + mock_ws.sock = mock_sock + ws_client_module.create_websocket(config, "ws://example.com") + mock_sock.setsockopt.assert_any_call(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + def test_create_websocket_applies_custom_socket_options(self): + """Verify create_websocket applies custom socket_options if configured.""" + config = Configuration() + custom_opts = [(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)] + config.socket_options = custom_opts + with patch.object(ws_client_module, 'WebSocket', autospec=True) as mock_ws_cls: + mock_ws = mock_ws_cls.return_value + mock_sock = MagicMock() + mock_ws.sock = mock_sock + ws_client_module.create_websocket(config, "ws://example.com") + mock_sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + def test_stream_request_forwards_ping_interval(self): + """Verify stream._websocket_request forwards ping_interval only when provided.""" + config = Configuration() + api_client = MagicMock() + api_client.configuration = config + + class DummyApi: + def __init__(self, client): + self.api_client = client + def sample_call(self, *args, **kwargs): + return self.api_client.call_api('GET', 'https://example.com') + + dummy = DummyApi(api_client) + + received_kwargs = {} + def mock_ws_request(conf, method, url, **kwargs): + received_kwargs.clear() + received_kwargs.update(kwargs) + return ws_client_module.WSResponse("ok", 200) + + from kubernetes.stream.stream import _websocket_request + + _websocket_request(mock_ws_request, None, dummy.sample_call, ping_interval=25) + self.assertEqual(received_kwargs.get('ping_interval'), 25) + self.assertNotIn('ping_timeout', received_kwargs) + + _websocket_request(mock_ws_request, None, dummy.sample_call) + self.assertNotIn('ping_interval', received_kwargs) + + def test_portforward_proxy_handles_ping_frame_with_single_pong(self): + """Verify PortForward._proxy handles incoming PING frame with a single PONG.""" + server_sock, client_sock = socket.socketpair() + try: + ws = websocket.WebSocket() + ws.sock = client_sock + ws.connected = True + + ping_payload = b'pf-ping' + ping_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_PING, 0, ping_payload).format() + close_frame = websocket.ABNF( + 1, 0, 0, 0, websocket.ABNF.OPCODE_CLOSE, 0, b'\x03\xe8').format() + server_sock.sendall(ping_frame + close_frame) + + with patch.object(ws, 'pong', wraps=ws.pong) as mock_pong: + pf = ws_client_module.PortForward(ws, [8080]) + try: + time.sleep(0.1) + mock_pong.assert_called_once_with(ping_payload) + finally: + pf.close() + finally: + server_sock.close() + client_sock.close() + + if __name__ == '__main__': unittest.main()