-
Notifications
You must be signed in to change notification settings - Fork 7.2k
[1/3] queue-based autoscaling - add queue monitor #59430
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
ad81408
add queue monitor
harshit-anyscale 1acaaf0
move pika and redis import inside actor
harshit-anyscale 90afee6
fix tests
harshit-anyscale ceb80ec
fix tests
harshit-anyscale d65d94d
review comments
harshit-anyscale 29cbde5
review changes
harshit-anyscale 091c25c
review changes
harshit-anyscale 931c3ca
review changes
harshit-anyscale 8140bcc
review changes
harshit-anyscale ab285ce
review changes
harshit-anyscale c550a52
review changes
harshit-anyscale 2abc81d
add more tests
harshit-anyscale 1f89f99
reivew changes
harshit-anyscale a5a0828
review changes
harshit-anyscale dd5175b
review changes
harshit-anyscale e026933
review changes
harshit-anyscale 844c966
review changes
harshit-anyscale ea3cb68
review changes
harshit-anyscale File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,336 @@ | ||
| import logging | ||
| from typing import Any, Dict | ||
|
|
||
| import ray | ||
| from ray.serve._private.constants import SERVE_LOGGER_NAME | ||
|
|
||
| logger = logging.getLogger(SERVE_LOGGER_NAME) | ||
|
|
||
| # Actor name prefix for QueueMonitor actors | ||
| QUEUE_MONITOR_ACTOR_PREFIX = "QUEUE_MONITOR::" | ||
|
|
||
|
|
||
| class QueueMonitorConfig: | ||
| """Configuration for the QueueMonitor deployment.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| broker_url: str, | ||
| queue_name: str, | ||
| ): | ||
| self.broker_url = broker_url | ||
| self.queue_name = queue_name | ||
|
|
||
| @property | ||
| def broker_type(self) -> str: | ||
| url_lower = self.broker_url.lower() | ||
| if url_lower.startswith("redis"): | ||
| return "redis" | ||
| elif url_lower.startswith("amqp") or url_lower.startswith("pyamqp"): | ||
| return "rabbitmq" | ||
| else: | ||
| return "unknown" | ||
|
|
||
|
|
||
| class QueueMonitor: | ||
|
|
||
| """ | ||
| Actor that monitors queue length by directly querying the broker. | ||
|
|
||
| Returns pending tasks in the queue. | ||
|
|
||
| Uses native broker clients: | ||
| - Redis: Uses redis-py library with LLEN command | ||
| - RabbitMQ: Uses pika library with passive queue declaration | ||
| """ | ||
|
|
||
| def __init__(self, config: QueueMonitorConfig): | ||
| self._config = config | ||
| self._last_queue_length: int = 0 | ||
| self._is_initialized: bool = False | ||
|
|
||
| # Redis connection state | ||
| self._redis_client: Any = None | ||
|
|
||
| # RabbitMQ connection state | ||
| self._rabbitmq_connection: Any = None | ||
| self._rabbitmq_channel: Any = None | ||
|
|
||
| def initialize(self) -> None: | ||
| """ | ||
| Initialize connection to the broker. | ||
|
|
||
| Creates the appropriate client based on broker type and tests the connection. | ||
| """ | ||
| if self._is_initialized: | ||
| return | ||
|
|
||
| broker_type = self._config.broker_type | ||
| try: | ||
| if broker_type == "redis": | ||
| self._init_redis() | ||
| elif broker_type == "rabbitmq": | ||
| self._init_rabbitmq() | ||
| else: | ||
| raise ValueError( | ||
| f"Unsupported broker type: {broker_type}. Supported: redis, rabbitmq" | ||
| ) | ||
|
|
||
| self._is_initialized = True | ||
| logger.info( | ||
| f"QueueMonitor initialized for queue '{self._config.queue_name}' (broker: {broker_type})" | ||
| ) | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Failed to initialize QueueMonitor: {e}") | ||
| raise | ||
|
|
||
| def _init_redis(self) -> None: | ||
| import redis | ||
|
|
||
| """Initialize Redis client.""" | ||
| self._redis_client = redis.from_url(self._config.broker_url) | ||
|
|
||
| # Test connection | ||
| self._redis_client.ping() | ||
|
|
||
| def _init_rabbitmq(self) -> None: | ||
| import pika | ||
|
|
||
| """Initialize RabbitMQ connection and channel.""" | ||
| # Store connection parameters for reconnection | ||
| self._rabbitmq_connection_params = pika.URLParameters(self._config.broker_url) | ||
|
|
||
| # Establish persistent connection and channel | ||
| self._rabbitmq_connection = pika.BlockingConnection( | ||
| self._rabbitmq_connection_params | ||
| ) | ||
| self._rabbitmq_channel = self._rabbitmq_connection.channel() | ||
|
|
||
| def _ensure_redis_connection(self) -> None: | ||
| """Ensure Redis connection is open, reconnecting if necessary.""" | ||
| import redis | ||
|
|
||
| needs_reconnect = self._redis_client is None | ||
| if not needs_reconnect: | ||
| try: | ||
| needs_reconnect = not self._redis_client.ping() | ||
| except redis.ConnectionError: | ||
| needs_reconnect = True | ||
|
|
||
| if needs_reconnect: | ||
| logger.warning("Redis connection lost, reconnecting...") | ||
| self._redis_client = redis.from_url(self._config.broker_url) | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def _ensure_rabbitmq_connection(self) -> None: | ||
| import pika | ||
|
|
||
| """Ensure RabbitMQ connection is open, reconnecting if necessary.""" | ||
| if ( | ||
| self._rabbitmq_connection is None | ||
| or self._rabbitmq_connection.is_closed | ||
| or self._rabbitmq_channel is None | ||
| or self._rabbitmq_channel.is_closed | ||
| ): | ||
| logger.warning("RabbitMQ connection lost, reconnecting...") | ||
| self._rabbitmq_connection = pika.BlockingConnection( | ||
| self._rabbitmq_connection_params | ||
| ) | ||
| self._rabbitmq_channel = self._rabbitmq_connection.channel() | ||
|
|
||
| def _get_redis_queue_length(self) -> int: | ||
| """ | ||
| Get pending tasks from Redis broker. | ||
|
|
||
| Returns: | ||
| Number of pending tasks in the queue. | ||
| """ | ||
| self._ensure_redis_connection() | ||
| return self._redis_client.llen(self._config.queue_name) | ||
|
|
||
| def _get_rabbitmq_queue_length(self) -> int: | ||
| """ | ||
| Get pending tasks from RabbitMQ broker. | ||
|
|
||
| Returns: | ||
| Number of pending (ready) messages in the queue. | ||
| """ | ||
| self._ensure_rabbitmq_connection() | ||
|
|
||
| # Passive declaration - doesn't create queue, just gets info | ||
| result = self._rabbitmq_channel.queue_declare( | ||
| queue=self._config.queue_name, passive=True | ||
| ) | ||
|
|
||
| return result.method.message_count | ||
|
|
||
| def get_config(self) -> Dict[str, Any]: | ||
| """ | ||
| Get the QueueMonitor configuration as a serializable dict. | ||
|
|
||
| Returns: | ||
| Dict with 'broker_url' and 'queue_name' keys | ||
| """ | ||
| return { | ||
| "broker_url": self._config.broker_url, | ||
| "queue_name": self._config.queue_name, | ||
| } | ||
|
|
||
| def get_queue_length(self) -> int: | ||
| """ | ||
| Get the current queue length from the broker. | ||
|
|
||
| Returns: | ||
| Number of pending tasks in the queue. | ||
| """ | ||
| if not self._is_initialized: | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| logger.warning( | ||
| f"QueueMonitor not initialized for queue '{self._config.queue_name}', returning 0" | ||
| ) | ||
| return 0 | ||
|
|
||
| try: | ||
| broker_type = self._config.broker_type | ||
|
|
||
| if broker_type == "redis": | ||
| queue_length = self._get_redis_queue_length() | ||
| elif broker_type == "rabbitmq": | ||
| queue_length = self._get_rabbitmq_queue_length() | ||
| else: | ||
| raise ValueError(f"Unsupported broker type: {broker_type}") | ||
|
|
||
| # Update cache | ||
| self._last_queue_length = queue_length | ||
|
|
||
| return queue_length | ||
|
|
||
| except Exception as e: | ||
| logger.warning( | ||
| f"Failed to query queue length: {e}. Using last known value: {self._last_queue_length}" | ||
| ) | ||
| return self._last_queue_length | ||
|
|
||
| def shutdown(self) -> None: | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Close Redis client if present | ||
| if getattr(self, "_redis_client", None) is not None: | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| try: | ||
| if hasattr(self._redis_client, "close"): | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self._redis_client.close() | ||
| except Exception as e: | ||
| logger.warning(f"Error closing Redis client: {e}") | ||
| self._redis_client = None | ||
|
|
||
| # Close RabbitMQ connection if present | ||
| if getattr(self, "_rabbitmq_connection", None) is not None: | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| try: | ||
| if not self._rabbitmq_connection.is_closed: | ||
| self._rabbitmq_connection.close() | ||
| except Exception as e: | ||
| logger.warning(f"Error closing RabbitMQ connection: {e}") | ||
| self._rabbitmq_connection = None | ||
| self._rabbitmq_channel = None | ||
|
|
||
| if hasattr(self, "_is_initialized"): | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self._is_initialized = False | ||
|
|
||
| def __del__(self): | ||
| self.shutdown() | ||
|
|
||
|
|
||
| @ray.remote(num_cpus=0, runtime_env={"pip": ["pika", "redis"]}) | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| class QueueMonitorActor(QueueMonitor): | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Ray actor version of QueueMonitor for direct access from ServeController. | ||
|
|
||
| This is used instead of a Serve deployment because the autoscaling policy | ||
| runs inside the ServeController, and using serve.get_deployment_handle() | ||
| from within the controller causes a deadlock. | ||
| """ | ||
|
|
||
| def __init__(self, config: QueueMonitorConfig): | ||
| super().__init__(config) | ||
| self.initialize() | ||
|
|
||
|
|
||
| def create_queue_monitor_actor( | ||
| deployment_name: str, | ||
| config: QueueMonitorConfig, | ||
| namespace: str = "serve", | ||
| ) -> ray.actor.ActorHandle: | ||
| """ | ||
| Create a named QueueMonitor Ray actor. | ||
|
|
||
| Args: | ||
| deployment_name: Name of the deployment | ||
| config: QueueMonitorConfig with broker URL and queue name | ||
| namespace: Ray namespace for the actor | ||
|
|
||
| Returns: | ||
| ActorHandle for the QueueMonitor actor | ||
| """ | ||
| full_actor_name = f"{QUEUE_MONITOR_ACTOR_PREFIX}{deployment_name}" | ||
|
|
||
| # Check if actor already exists | ||
| try: | ||
| existing = ray.get_actor(full_actor_name, namespace=namespace) | ||
| logger.info(f"QueueMonitor actor '{full_actor_name}' already exists, reusing") | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return existing | ||
harshit-anyscale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| except ValueError: | ||
| pass # Actor doesn't exist, create it | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| actor = QueueMonitorActor.options( | ||
| name=full_actor_name, | ||
| namespace=namespace, | ||
| ).remote(config) | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| logger.info( | ||
| f"Created QueueMonitor actor '{full_actor_name}' in namespace '{namespace}'" | ||
| ) | ||
| return actor | ||
|
|
||
|
|
||
| def get_queue_monitor_actor( | ||
| deployment_name: str, | ||
| namespace: str = "serve", | ||
| ) -> ray.actor.ActorHandle: | ||
| """ | ||
| Get an existing QueueMonitor actor by name. | ||
|
|
||
| Args: | ||
| deployment_name: Name of the deployment | ||
| namespace: Ray namespace | ||
|
|
||
| Returns: | ||
| ActorHandle for the QueueMonitor actor | ||
|
|
||
| Raises: | ||
| ValueError: If actor doesn't exist | ||
| """ | ||
| full_actor_name = f"{QUEUE_MONITOR_ACTOR_PREFIX}{deployment_name}" | ||
| return ray.get_actor(full_actor_name, namespace=namespace) | ||
|
|
||
|
|
||
| def delete_queue_monitor_actor( | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| deployment_name: str, | ||
| namespace: str = "serve", | ||
| ) -> bool: | ||
| """ | ||
| Delete a QueueMonitor actor by name. | ||
|
|
||
| Args: | ||
| deployment_name: Name of the deployment | ||
| namespace: Ray namespace | ||
|
|
||
| Returns: | ||
| True if actor was deleted, False if it didn't exist | ||
| """ | ||
| full_actor_name = f"{QUEUE_MONITOR_ACTOR_PREFIX}{deployment_name}" | ||
| try: | ||
| actor = ray.get_actor(full_actor_name, namespace=namespace) | ||
| ray.kill(actor) | ||
| logger.info(f"Deleted QueueMonitor actor '{full_actor_name}'") | ||
harshit-anyscale marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return True | ||
| except ValueError: | ||
| # Actor doesn't exist | ||
| return False | ||
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.