[Security] Fix P2P ZMQ socket exhaustion via unbounded peer sessions (#51504)
Signed-off-by: jperezde <jperezde@redhat.com> Signed-off-by: Juan Pérez de Algaba <jperezde@redhat.com> Co-authored-by: Robert Shaw <114415538+robertgshaw2-redhat@users.noreply.github.com> Co-authored-by: Itay Etelis <92247226+Etelis@users.noreply.github.com>
This commit is contained in:
co-authored by
Robert Shaw
Itay Etelis
parent
239a3fa3a8
commit
93d2cab35e
@@ -27,11 +27,35 @@ _HEARTBEAT_IVL_MS = 2000
|
||||
_HEARTBEAT_TIMEOUT_MS = 10000
|
||||
_HEARTBEAT_TTL_MS = 10000
|
||||
|
||||
# Events that indicate a fatal connection failure — the peer will never
|
||||
# become reachable through this socket.
|
||||
_FATAL_MONITOR_EVENTS: frozenset[int] = frozenset() # populated after import
|
||||
|
||||
# Shared sentinels returned when there is nothing to report.
|
||||
_EMPTY_INBOX: tuple[dict, ...] = ()
|
||||
_EMPTY_NEW_CONNECTIONS: tuple[ControlConnection, ...] = ()
|
||||
|
||||
|
||||
def _build_fatal_events() -> frozenset[int]:
|
||||
events = {zmq.EVENT_DISCONNECTED, zmq.EVENT_CLOSED}
|
||||
for attr in (
|
||||
"EVENT_HANDSHAKE_FAILED_AUTH",
|
||||
"EVENT_HANDSHAKE_FAILED_PROTOCOL",
|
||||
"EVENT_HANDSHAKE_FAILED_NO_DETAIL",
|
||||
):
|
||||
val = getattr(zmq, attr, None)
|
||||
if val is not None:
|
||||
events.add(val)
|
||||
return frozenset(events)
|
||||
|
||||
|
||||
_FATAL_MONITOR_EVENTS = _build_fatal_events()
|
||||
|
||||
_MONITOR_EVENT_MASK: int = 0
|
||||
for _ev in _FATAL_MONITOR_EVENTS:
|
||||
_MONITOR_EVENT_MASK |= _ev
|
||||
|
||||
|
||||
def _tcp_addr(host: str, port: int | str) -> str:
|
||||
return f"tcp://{host}:{port}"
|
||||
|
||||
@@ -247,7 +271,7 @@ class ZmqTransport(ControlTransport):
|
||||
safe_id = peer_id.replace(":", "-").replace("/", "-")
|
||||
monitor_addr = f"inproc://p2p-monitor-{safe_id}-{self._monitor_seq}"
|
||||
self._monitor_seq += 1
|
||||
dealer.monitor(monitor_addr, zmq.EVENT_DISCONNECTED)
|
||||
dealer.monitor(monitor_addr, _MONITOR_EVENT_MASK)
|
||||
|
||||
monitor_sock = self._zmq_ctx.socket(zmq.PAIR)
|
||||
monitor_sock.connect(monitor_addr)
|
||||
@@ -319,29 +343,33 @@ class ZmqTransport(ControlTransport):
|
||||
self._pending_inbound.append((sender_id, msg))
|
||||
|
||||
def _check_monitors(self) -> None:
|
||||
"""Non-blocking: check all monitor sockets for disconnection."""
|
||||
"""Non-blocking: check all monitor sockets for fatal events."""
|
||||
for conn in self._connections.values():
|
||||
if not conn.alive:
|
||||
continue
|
||||
try:
|
||||
event = zmq.utils.monitor.recv_monitor_message(
|
||||
conn.monitor_socket, zmq.NOBLOCK
|
||||
)
|
||||
except zmq.Again:
|
||||
continue
|
||||
except zmq.ZMQError as exc:
|
||||
logger.warning(
|
||||
"ZmqTransport %s: monitor error for peer %s: %s",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
while True:
|
||||
try:
|
||||
event = zmq.utils.monitor.recv_monitor_message(
|
||||
conn.monitor_socket, zmq.NOBLOCK
|
||||
)
|
||||
except zmq.Again:
|
||||
break
|
||||
except zmq.ZMQError as exc:
|
||||
logger.warning(
|
||||
"ZmqTransport %s: monitor error for peer %s: %s",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
exc,
|
||||
)
|
||||
break
|
||||
|
||||
if event["event"] == zmq.EVENT_DISCONNECTED:
|
||||
logger.debug(
|
||||
"ZmqTransport %s: peer %s disconnected",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
)
|
||||
conn.mark_dead()
|
||||
ev = event["event"]
|
||||
if ev in _FATAL_MONITOR_EVENTS:
|
||||
logger.debug(
|
||||
"ZmqTransport %s: peer %s fatal event 0x%x",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
ev,
|
||||
)
|
||||
conn.mark_dead()
|
||||
break
|
||||
|
||||
@@ -69,6 +69,11 @@ _SHUTDOWN_DRAIN_TIMEOUT_S = 3.0
|
||||
# enough to avoid busy-spinning the scheduler thread.
|
||||
_DRAIN_SLEEP_S = 0.001
|
||||
|
||||
# Idle sessions are only reaped when remaining capacity is at most this
|
||||
# many slots. Session setup is expensive; below this headroom, keep idle
|
||||
# peers so a later burst does not pay handshake again.
|
||||
_IDLE_REAP_HEADROOM = 8
|
||||
|
||||
|
||||
def _remote_prefiller_params(kv_params: dict | None) -> dict | None:
|
||||
"""Return the ``remote_prefiller`` sub-dict, or None if absent.
|
||||
@@ -428,7 +433,9 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
_annotate_req_context(req_context)
|
||||
source = req_context.get_state(P2PSourceInfo)
|
||||
if source is not None:
|
||||
self._get_or_create_session(source.peer_id)
|
||||
session = self._get_or_create_session(source.peer_id)
|
||||
if session is None:
|
||||
self._failed_req_ids.add(source.kv_request_id)
|
||||
dest = req_context.get_state(P2PDestInfo)
|
||||
if dest is not None and dest.kv_request_id:
|
||||
return RequestOffloadingContext(policy=OffloadPolicy.REQUEST_LEVEL)
|
||||
@@ -685,38 +692,78 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
self._hash_seed = get_none_hash_seed()
|
||||
return self._hash_seed
|
||||
|
||||
def _get_or_create_session(self, peer_id: str) -> P2PSession:
|
||||
def _get_or_create_session(self, peer_id: str) -> P2PSession | None:
|
||||
"""Return the existing session for peer_id, or open one outbound.
|
||||
|
||||
Consumer-side helper for on_new_request: when ``remote_prefiller``
|
||||
(PD) or ``remote_kv_source`` (symmetric P2P) is set, the consumer must reach the
|
||||
producer at peer_id. If we already have a session toward that
|
||||
peer (from a prior load or a peer-initiated inbound), reuse it;
|
||||
otherwise open an outbound ControlConnection and build a
|
||||
(PD) or ``remote_kv_source`` (symmetric P2P) is set, the consumer
|
||||
must reach the producer at peer_id. If we already have a session
|
||||
toward that peer (from a prior load or a peer-initiated inbound),
|
||||
reuse it; otherwise open an outbound ControlConnection and build a
|
||||
connected session.
|
||||
|
||||
Returns None if the session could not be created (capacity
|
||||
exceeded or transport error).
|
||||
"""
|
||||
session = self._sessions.get(peer_id)
|
||||
if session is not None:
|
||||
return session
|
||||
conn = self._control.connect(peer_id)
|
||||
session = P2PSession(
|
||||
peer_id=peer_id,
|
||||
local_id=self._local_id,
|
||||
transport=self._data,
|
||||
local_block_len=self._data.block_len,
|
||||
local_hash_seed=self._get_hash_seed(),
|
||||
conn=conn,
|
||||
)
|
||||
|
||||
max_peers = envs.VLLM_P2P_MAX_PEERS
|
||||
if len(self._sessions) >= max_peers:
|
||||
logger.warning(
|
||||
"P2P %s: rejecting outbound peer %s — session limit "
|
||||
"reached (%d/%d). Set VLLM_P2P_MAX_PEERS to increase.",
|
||||
self._local_id,
|
||||
peer_id,
|
||||
len(self._sessions),
|
||||
max_peers,
|
||||
)
|
||||
return None
|
||||
|
||||
conn = None
|
||||
try:
|
||||
conn = self._control.connect(peer_id)
|
||||
session = P2PSession(
|
||||
peer_id=peer_id,
|
||||
local_id=self._local_id,
|
||||
transport=self._data,
|
||||
local_block_len=self._data.block_len,
|
||||
local_hash_seed=self._get_hash_seed(),
|
||||
conn=conn,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"P2P %s: failed to open connection to %s",
|
||||
self._local_id,
|
||||
peer_id,
|
||||
)
|
||||
if conn is not None:
|
||||
conn.close()
|
||||
return None
|
||||
|
||||
self._sessions[peer_id] = session
|
||||
return session
|
||||
|
||||
def _accept_new_peers(self, new_connections: Sequence[ControlConnection]) -> None:
|
||||
max_peers = envs.VLLM_P2P_MAX_PEERS
|
||||
for conn in new_connections:
|
||||
logger.info(
|
||||
"P2P %s: accepting incoming connection from %s",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
)
|
||||
if len(self._sessions) >= max_peers:
|
||||
logger.warning(
|
||||
"P2P %s: rejecting inbound peer %s — session limit "
|
||||
"reached (%d/%d). Set VLLM_P2P_MAX_PEERS to increase.",
|
||||
self._local_id,
|
||||
conn.peer_id,
|
||||
len(self._sessions),
|
||||
max_peers,
|
||||
)
|
||||
conn.close()
|
||||
continue
|
||||
try:
|
||||
existing = self._sessions.get(conn.peer_id)
|
||||
if existing is not None:
|
||||
@@ -827,6 +874,53 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
len(batches),
|
||||
)
|
||||
|
||||
def _reap_idle_sessions(self) -> None:
|
||||
"""Evict idle sessions when remaining peer slots are scarce.
|
||||
|
||||
A session is idle when it has no pending work and its last activity
|
||||
timestamp exceeds ``VLLM_P2P_IDLE_TIMEOUT_S``. Eviction runs only
|
||||
when ``len(_sessions) >= VLLM_P2P_MAX_PEERS - _IDLE_REAP_HEADROOM``
|
||||
so a quiet but healthy mesh is not torn down. Uses the same
|
||||
teardown path as ``_reap_dead_sessions``.
|
||||
"""
|
||||
idle_timeout = envs.VLLM_P2P_IDLE_TIMEOUT_S
|
||||
if idle_timeout <= 0:
|
||||
return
|
||||
max_peers = envs.VLLM_P2P_MAX_PEERS
|
||||
headroom = min(_IDLE_REAP_HEADROOM, max(0, max_peers - 1))
|
||||
if len(self._sessions) < max_peers - headroom:
|
||||
return
|
||||
deadline = time.monotonic() - idle_timeout
|
||||
idle: list[str] | None = None
|
||||
for pid, s in self._sessions.items():
|
||||
if not s.has_pending_work and s.last_activity_at <= deadline:
|
||||
if idle is None:
|
||||
idle = []
|
||||
idle.append(pid)
|
||||
if idle is None:
|
||||
return
|
||||
for pid in idle:
|
||||
session = self._sessions.pop(pid)
|
||||
stale_kv_ids = [
|
||||
kid for kid, s in self._kv_to_session.items() if s is session
|
||||
]
|
||||
for kid in stale_kv_ids:
|
||||
del self._kv_to_session[kid]
|
||||
close_result = session.close()
|
||||
for job_id in close_result.failed_jobs:
|
||||
self._finished_jobs.append(JobResult(job_id=job_id, success=False))
|
||||
for job_id in close_result.failed_stores:
|
||||
self._finished_jobs.append(JobResult(job_id=job_id, success=False))
|
||||
self._failed_req_ids.update(close_result.failed_req_ids)
|
||||
self._failed_serve_ctxs.extend(close_result.failed_serves)
|
||||
self._data.remove_remote_peer(pid)
|
||||
logger.info(
|
||||
"P2P %s: evicted idle peer %s (idle > %ds)",
|
||||
self._local_id,
|
||||
pid,
|
||||
idle_timeout,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Polling
|
||||
# ------------------------------------------------------------------
|
||||
@@ -893,6 +987,7 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
self._reap_dead_sessions()
|
||||
self._reap_unbound_stores()
|
||||
self._reap_idle_sessions()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
|
||||
@@ -18,9 +18,11 @@ received our ConnectMsg, after which queued outgoing messages are flushed.
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.kv_offload.base import OffloadKey
|
||||
from vllm.v1.kv_offload.tiering.p2p.control.base import ControlConnection
|
||||
@@ -128,6 +130,10 @@ class P2PSession:
|
||||
# Consecutive non-protocol dispatch errors. Reset on success.
|
||||
self._dispatch_error_count: int = 0
|
||||
|
||||
now = time.monotonic()
|
||||
self._connected_at: float | None = None
|
||||
self._last_activity_at: float = now
|
||||
|
||||
# kv_request_ids whose FetchMsg arrived during the current poll
|
||||
# tick. Drained and returned in the next poll() result so the
|
||||
# manager can bind kv_request_id → session and replay any
|
||||
@@ -168,6 +174,11 @@ class P2PSession:
|
||||
"""True while inbound loads or outbound transfers are outstanding."""
|
||||
return self._client.has_active_loads or self._server.has_inflight_transfers
|
||||
|
||||
@property
|
||||
def last_activity_at(self) -> float:
|
||||
"""Monotonic timestamp of the last meaningful session activity."""
|
||||
return self._last_activity_at
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Connection lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
@@ -181,6 +192,9 @@ class P2PSession:
|
||||
if self._conn is not None:
|
||||
raise ValueError(f"P2PSession {self.peer_id}: already connected")
|
||||
self._conn = conn
|
||||
now = time.monotonic()
|
||||
self._connected_at = now
|
||||
self._last_activity_at = now
|
||||
self._send_connect()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -249,17 +263,39 @@ class P2PSession:
|
||||
def poll(self) -> SessionPollResult:
|
||||
"""Process incoming messages, drive transfers, apply timeouts."""
|
||||
if self._conn is None:
|
||||
# Pending session — store-job timeouts still apply so buffered
|
||||
# jobs that never get picked up are surfaced as failures.
|
||||
return SessionPollResult(
|
||||
loads=[],
|
||||
stores=self._server.collect_idle_timeouts(),
|
||||
new_fetch_ids=[],
|
||||
)
|
||||
|
||||
for msg in self._conn.recv():
|
||||
# Drain the inbox first so a ConnectAck already buffered at the
|
||||
# deadline (e.g. after a scheduler stall) can complete the
|
||||
# handshake instead of being discarded by mark_dead.
|
||||
messages = self._conn.recv()
|
||||
if messages:
|
||||
self._last_activity_at = time.monotonic()
|
||||
for msg in messages:
|
||||
self._on_message(msg)
|
||||
|
||||
# Handshake deadline: a peer that never completes the handshake
|
||||
# is stuck in connected-but-not-ready state. Mark it dead so the
|
||||
# manager reaps it instead of accumulating sockets indefinitely.
|
||||
if (
|
||||
not self._send_ready
|
||||
and self._conn.alive
|
||||
and self._connected_at is not None
|
||||
and time.monotonic() - self._connected_at
|
||||
> envs.VLLM_P2P_HANDSHAKE_TIMEOUT_S
|
||||
):
|
||||
logger.warning(
|
||||
"P2PSession %s: handshake timed out after %ds "
|
||||
"— marking connection dead",
|
||||
self.peer_id,
|
||||
envs.VLLM_P2P_HANDSHAKE_TIMEOUT_S,
|
||||
)
|
||||
self._conn.mark_dead()
|
||||
|
||||
loads = self._client.collect_results()
|
||||
stores = self._server.collect_results()
|
||||
self._server.drain_pending_aborts()
|
||||
@@ -533,6 +569,7 @@ class P2PSession:
|
||||
return
|
||||
try:
|
||||
self._conn.send(msg)
|
||||
self._last_activity_at = time.monotonic()
|
||||
logger.debug("P2PSession %s: sent %s", self.peer_id, msg.get(TYPE_KEY))
|
||||
except Exception:
|
||||
# A send failure means the connection is broken. Swallowing it
|
||||
|
||||
Reference in New Issue
Block a user