Repository navigation
fix(stream): implement RFC 6455 WebSocket ping/pong heartbeats and TCP keepalive (#1841) - #2807
YuvrajLamba01 wants to merge 2 commits into
Conversation
…P keepalive (kubernetes-client#1841) Long running streaming commands (such as exec, attach, and port-forward) frequently fail with WebSocketConnectionClosedException or silent socket drops when passing through idle proxies, firewalls, and load balancers due to lack of heartbeats. Furthermore, kube-apiserver ping frames were unhandled. This patch: - Adds a background heartbeat daemon thread in WSClient that periodically sends RFC 6455 Ping frames at ping_interval (defaults to 30s when configuration.keep_alive is True, or configured via ws_ping_interval). - Handles incoming ABNF.OPCODE_PING frames in WSClient and PortForward, automatically responding with ABNF.OPCODE_PONG containing the received payload. - Records _last_pong_time upon receiving ABNF.OPCODE_PONG frames and supports ws_ping_timeout for dead-connection detection. - Applies TCP keepalive socket options (tcp_keepalive_socket_options) and custom configuration.socket_options in create_websocket. - Adds ping_interval and ping_timeout support to stream() and websocket_call(). - Adds comprehensive unit test coverage in WSClientPingPongTest. Signed-off-by: Yuvraj Lamba <yuvrajlamba5151@gmail.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: YuvrajLamba01 The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
| if hasattr(self, '_ping_stop_event') and self._ping_stop_event: | ||
| self._ping_stop_event.set() | ||
| return | ||
| elif op_code == ABNF.OPCODE_PING: |
There was a problem hiding this comment.
websocket-client's recv_data_frame already replies to a ping with a pong before returning the frame, so this sends a second pong (assert_called_with in the test didn't catch the duplicate call). Let's drop this branch and the one in _proxy, and update the PR description.
There was a problem hiding this comment.
Good catch — removed the duplicate ABNF.OPCODE_PING pong branches from WSClient.update and PortForward._proxy in commit e9301190a (restoring ABNF.OPCODE_PING in _proxy's ignored control-frame tuple). Updated both ping tests to assert mock_pong.assert_called_once_with(ping_payload) and updated the PR description.
| if isinstance(interval, (int, float)): | ||
| self._ping_interval = interval | ||
| if self._ping_interval is None and configuration and getattr(configuration, 'keep_alive', False) is True: | ||
| self._ping_interval = 30 |
There was a problem hiding this comment.
keep_alive is documented on Configuration as TCP keepalive only. Turning it on here also starts a ping thread per stream, which changes behavior for existing callers. Let's keep app-level pings opt-in via ping_interval and drop the undocumented ws_ping_interval/ws_ping_timeout lookups.
There was a problem hiding this comment.
Updated in e9301190a — dropped ws_ping_interval/ws_ping_timeout configuration lookups and keep_alive auto-starting a ping thread so keep_alive=True remains TCP keepalive only and app-level pings stay strictly opt-in via ping_interval.
| if (self._ping_timeout and self._last_ping_time and | ||
| (self._last_pong_time is None or self._last_pong_time < self._last_ping_time)): | ||
| if time.time() - self._last_ping_time > self._ping_timeout: | ||
| self.close() |
There was a problem hiding this comment.
_last_pong_time is only updated when the caller calls update(). With _preload_content=False, an idle caller leaves pong frames unread in the socket buffer, so ping_timeout < ping_interval closes a healthy stream, while ping_timeout >= ping_interval never triggers because _last_ping_time is reset on every send; self.close() from this thread also calls recv_frame() without a lock and races with update(). Let's drop ping_timeout (TCP keepalive plus outbound ping_interval already cover #1841).
There was a problem hiding this comment.
Removed ping_timeout, _last_pong_time, ABNF.OPCODE_PONG tracking, and self.close() from _send_ping_worker in e9301190a. The heartbeat thread now only invokes self.sock.ping() under ping_interval and exits cleanly when _ping_stop_event is set or sending fails.
Signed-off-by: Yuvraj Lamba <yuvrajlamba5151@gmail.com>
What type of PR is this?
/kind bug
What this PR does / why we need it:
Long-running streaming commands (
exec,attach, andport-forward) viastream()orportforward()can drop silently or raiseWebSocketConnectionClosedExceptionwhen passing through idle intermediate proxies, firewalls, or load balancers (such as AWS ALB, Envoy, or NGINX).This PR adds opt-in application-level RFC 6455 WebSocket
Pingheartbeats alongside TCP keepalive socket options inkubernetes/stream/:WSClient): Acceptsping_intervalonWSClient,websocket_call(), andstream()(forwarded only when explicitly provided). Whenping_interval > 0(excluding booleans), a daemon thread sends periodic RFC 6455Pingcontrol frames viaself.sock.ping()untilclose(),run_forever()completion, or receivingABNF.OPCODE_CLOSE.websocket-client'srecv_data_frame(True)automaticPongreply in bothWSClient.update()andPortForward._proxy()rather than sending a second pong frame.create_websocket): Appliesconfiguration.socket_optionsif configured, ortcp_keepalive_socket_options()whenconfiguration.keep_alive is True. Keepingconfiguration.keep_alivescoped solely to TCP keepalive preserves existing behavior for callers unlessping_intervalis explicitly passed.ping_intervalforwarding and validation, keepingkeep_alive=Truescoped to TCP keepalive, applying TCP/custom socket options increate_websocket, and asserting single-pong replies viamock_pong.assert_called_once_with(...)inWSClient.update()andPortForward._proxy().Which issue(s) this PR fixes:
Fixes #1841
Special notes for your reviewer:
Verified locally on Windows (Python 3.14) across
kubernetes/stream/stream_test.py,kubernetes/utils/keepalive_test.py, andWSClientPingPongTest/CreateWebsocketCaCertDataTest/ non-select.polltests inkubernetes/stream/ws_client_test.py.Does this PR introduce a user-facing change?
Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.: