Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions kubernetes/stream/stream_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,27 @@ def websocket_call(configuration, method, url, **kwargs):
)
self.assertIn('command=echo&command=hello', request['url'])

def test_generated_api_request_passes_tuple_request_timeout(self):
request = {}

def websocket_call(configuration, method, url, **kwargs):
request.update(method=method, url=url, kwargs=kwargs)
return ws_client.WSResponse(data='output', status=200)

api = client.CoreV1Api()
output = _websocket_request(
websocket_call,
None,
api.connect_get_namespaced_pod_exec,
'pod',
'default',
command=['date'],
_request_timeout=(5, 10),
)

self.assertEqual('output', output)
self.assertEqual((5, 10), request['kwargs'].get('_request_timeout'))


if __name__ == '__main__':
unittest.main()
36 changes: 25 additions & 11 deletions kubernetes/stream/ws_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def getvalue(self):


class WSClient:
def __init__(self, configuration, url, headers, capture_all, binary=False):
def __init__(self, configuration, url, headers, capture_all, binary=False,
_request_timeout=None):
"""A websocket client with support for channels.

Exec command uses different channels for different streams. for
Expand All @@ -67,7 +68,8 @@ def __init__(self, configuration, url, headers, capture_all, binary=False):
self._all = StringIO() if not self.binary else BytesIO()
else:
self._all = _IgnoredIO()
self.sock = create_websocket(configuration, url, headers)
self.sock = create_websocket(
configuration, url, headers, _request_timeout=_request_timeout)
self.subprotocol = getattr(self.sock, 'subprotocol', None)
if not self.subprotocol and self.sock:
headers_dict = self.sock.getheaders()
Expand Down Expand Up @@ -300,12 +302,15 @@ def run_forever(self, timeout=None):
"""Wait till connection is closed or timeout reached. Buffer any input
received during this time."""
if timeout:
start = time.time()
while self.is_open() and time.time() - start < timeout:
self.update(timeout=(timeout - time.time() + start))
else:
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)
@property
def returncode(self):
"""
Expand Down Expand Up @@ -543,7 +548,7 @@ def get_websocket_url(url, query_params=None):
return urlunparse(parts)


def create_websocket(configuration, url, headers=None):
def create_websocket(configuration, url, headers=None, _request_timeout=None):
enableTrace(False)

# We just need to pass the Authorization, ignore all the other
Expand Down Expand Up @@ -579,6 +584,13 @@ def create_websocket(configuration, url, headers=None):
'header': header
}

if _request_timeout:
if isinstance(_request_timeout, (int, float)):
connect_opt['timeout'] = _request_timeout
elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2:
if _request_timeout[0] is not None:
connect_opt['timeout'] = _request_timeout[0]

if configuration.proxy or configuration.proxy_headers:
connect_opt = websocket_proxycare(connect_opt, configuration, url, headers)

Expand Down Expand Up @@ -617,7 +629,8 @@ def websocket_call(configuration, _method, url, **kwargs):
capture_all = kwargs.get("capture_all", True)
binary = kwargs.get('binary', False)
try:
client = WSClient(configuration, url, headers, capture_all, binary=binary)
client = WSClient(configuration, url, headers, capture_all, binary=binary,
_request_timeout=_request_timeout)
if not _preload_content:
return client
client.run_forever(timeout=_request_timeout)
Expand Down Expand Up @@ -659,7 +672,8 @@ def portforward_call(configuration, _method, url, **kwargs):
headers = kwargs.get("headers")

try:
websocket = create_websocket(configuration, url, headers)
websocket = create_websocket(configuration, url, headers,
_request_timeout=kwargs.get("_request_timeout"))
return PortForward(websocket, ports)
except (Exception, KeyboardInterrupt, SystemExit) as e:
raise ApiException(status=0, reason=str(e))
63 changes: 63 additions & 0 deletions kubernetes/stream/ws_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,69 @@ def test_create_websocket_header(self):
expected_header = f"sec-websocket-protocol: {V5_CHANNEL_PROTOCOL},{V4_CHANNEL_PROTOCOL}"
self.assertIn(expected_header, kwargs['header'])

def test_create_websocket_tuple_timeout(self):
"""Verify _request_timeout tuple sets connect timeout on connect"""
with patch.object(
ws_client_module, 'WebSocket', autospec=True
) as mock_ws_cls:
mock_ws = mock_ws_cls.return_value
ws_client_module.create_websocket(
self.config_mock, "ws://test", headers=None,
_request_timeout=(5, 10))
mock_ws.connect.assert_called_once()
kwargs = mock_ws.connect.call_args[1]
self.assertEqual(kwargs.get('timeout'), 5)

def test_create_websocket_scalar_timeout(self):
"""Verify scalar _request_timeout sets connect timeout on connect"""
with patch.object(
ws_client_module, 'WebSocket', autospec=True
) as mock_ws_cls:
mock_ws = mock_ws_cls.return_value
ws_client_module.create_websocket(
self.config_mock, "ws://test", headers=None,
_request_timeout=15)
mock_ws.connect.assert_called_once()
kwargs = mock_ws.connect.call_args[1]
self.assertEqual(kwargs.get('timeout'), 15)

def test_run_forever_tuple_timeout(self):
"""Verify run_forever handles tuple timeout without TypeError"""
with patch.object(ws_client_module, 'create_websocket'):
client = ws_client_module.WSClient(
self.config_mock, "ws://test", headers=None,
capture_all=True)
with patch.object(client, 'is_open', side_effect=[True, False]), \
patch.object(client, 'update') as mock_update:
client.run_forever(timeout=(5, 10))
mock_update.assert_called_once()
self.assertIsInstance(
mock_update.call_args[1]['timeout'], float)

def test_run_forever_tuple_timeout_none_read(self):
"""Verify run_forever handles (connect, None) tuple timeout"""
with patch.object(ws_client_module, 'create_websocket'):
client = ws_client_module.WSClient(
self.config_mock, "ws://test", headers=None,
capture_all=True)
with patch.object(client, 'is_open', side_effect=[True, False]), \
patch.object(client, 'update') as mock_update:
client.run_forever(timeout=(5, None))
mock_update.assert_called_once_with(timeout=None)

def test_websocket_call_passes_tuple_request_timeout(self):
"""Verify websocket_call forwards tuple _request_timeout"""
with patch.object(ws_client_module, 'WSClient') as mock_client_cls:
mock_client = mock_client_cls.return_value
mock_client.read_all.return_value = ['output']
ws_client_module.websocket_call(
self.config_mock, 'GET', 'http://test/exec',
_request_timeout=(5, 10))
mock_client_cls.assert_called_once()
self.assertEqual(
mock_client_cls.call_args[1].get('_request_timeout'), (5, 10))
mock_client.run_forever.assert_called_once_with(timeout=(5, 10))

def test_close_channel_v5(self):
"""Verify close_channel sends correct frame when v5 is negotiated"""
with patch.object(ws_client_module, 'create_websocket') as mock_create:
Expand Down