Skip to content

fix(stream): implement RFC 6455 WebSocket ping/pong heartbeats and TCP keepalive (#1841) - #2807

Open
YuvrajLamba01 wants to merge 2 commits into
kubernetes-client:masterfrom
YuvrajLamba01:stream-ping-pong-heartbeats-1841
Open

YuvrajLamba01 wants to merge 2 commits into
kubernetes-client:masterfrom
YuvrajLamba01:stream-ping-pong-heartbeats-1841

Conversation

@YuvrajLamba01

@YuvrajLamba01 YuvrajLamba01 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind bug

What this PR does / why we need it:

Long-running streaming commands (exec, attach, and port-forward) via stream() or portforward() can drop silently or raise WebSocketConnectionClosedException when 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 Ping heartbeats alongside TCP keepalive socket options in kubernetes/stream/:

  1. Opt-in Background Ping Worker (WSClient): Accepts ping_interval on WSClient, websocket_call(), and stream() (forwarded only when explicitly provided). When ping_interval > 0 (excluding booleans), a daemon thread sends periodic RFC 6455 Ping control frames via self.sock.ping() until close(), run_forever() completion, or receiving ABNF.OPCODE_CLOSE.
  2. Incoming Ping Handling Preserved Without Duplicates: Relies on websocket-client's recv_data_frame(True) automatic Pong reply in both WSClient.update() and PortForward._proxy() rather than sending a second pong frame.
  3. TCP Keepalive & Custom Socket Options (create_websocket): Applies configuration.socket_options if configured, or tcp_keepalive_socket_options() when configuration.keep_alive is True. Keeping configuration.keep_alive scoped solely to TCP keepalive preserves existing behavior for callers unless ping_interval is explicitly passed.
  4. Unit Tests: Covers opt-in ping_interval forwarding and validation, keeping keep_alive=True scoped to TCP keepalive, applying TCP/custom socket options in create_websocket, and asserting single-pong replies via mock_pong.assert_called_once_with(...) in WSClient.update() and PortForward._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, and WSClientPingPongTest / CreateWebsocketCaCertDataTest / non-select.poll tests in kubernetes/stream/ws_client_test.py.

Does this PR introduce a user-facing change?

Added opt-in `ping_interval` support for WebSocket `Ping` heartbeats in `stream()` / `WSClient` and applied TCP keepalive (`configuration.keep_alive`) / `configuration.socket_options` in `create_websocket()`.

Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:


…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>
@kubernetes-prow kubernetes-prow Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. kind/bug Categorizes issue or PR as related to a bug. cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. labels Nov 24, 2026
@kubernetes-prow
kubernetes-prow Bot requested review from roycaihw and yliaog November 24, 2026 11:07
@kubernetes-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: YuvrajLamba01
Once this PR has been reviewed and has the lgtm label, please assign yliaog for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubernetes-prow kubernetes-prow Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Nov 24, 2026
Comment thread kubernetes/stream/ws_client.py Outdated
if hasattr(self, '_ping_stop_event') and self._ping_stop_event:
self._ping_stop_event.set()
return
elif op_code == ABNF.OPCODE_PING:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread kubernetes/stream/ws_client.py Outdated
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread kubernetes/stream/ws_client.py Outdated
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()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@YuvrajLamba01

Copy link
Copy Markdown
Contributor Author

@roycaihw Thanks for the thorough review! Addressed all three points in commit e930119 and updated the PR description accordingly. Ready for another look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. kind/bug Categorizes issue or PR as related to a bug. release-note Denotes a PR that will be considered when it comes time to generate release notes. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unexpected WebSocketConnectionClosedException when streaming long running commands, missing pings?

2 participants