|
| 1 | +# Copyright The Lightning AI team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Port allocation manager to prevent race conditions in distributed training.""" |
| 15 | + |
| 16 | +import atexit |
| 17 | +import socket |
| 18 | +import threading |
| 19 | +from collections.abc import Iterator |
| 20 | +from contextlib import contextmanager |
| 21 | +from typing import Optional |
| 22 | + |
| 23 | + |
| 24 | +class PortManager: |
| 25 | + """Thread-safe port manager to prevent EADDRINUSE errors. |
| 26 | +
|
| 27 | + This manager maintains a global registry of allocated ports to ensure that multiple concurrent tests don't try to |
| 28 | + use the same port. While this doesn't completely eliminate the race condition with external processes, it prevents |
| 29 | + internal collisions within the test suite. |
| 30 | +
|
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self) -> None: |
| 34 | + self._lock = threading.Lock() |
| 35 | + self._allocated_ports: set[int] = set() |
| 36 | + # Register cleanup to release all ports on exit |
| 37 | + atexit.register(self.release_all) |
| 38 | + |
| 39 | + def allocate_port(self, preferred_port: Optional[int] = None, max_attempts: int = 100) -> int: |
| 40 | + """Allocate a free port, ensuring it's not already reserved. |
| 41 | +
|
| 42 | + Args: |
| 43 | + preferred_port: If provided, try to allocate this specific port first |
| 44 | + max_attempts: Maximum number of attempts to find a free port |
| 45 | +
|
| 46 | + Returns: |
| 47 | + An allocated port number |
| 48 | +
|
| 49 | + Raises: |
| 50 | + RuntimeError: If unable to find a free port after max_attempts |
| 51 | +
|
| 52 | + """ |
| 53 | + with self._lock: |
| 54 | + # If a preferred port is specified and available, use it |
| 55 | + if ( |
| 56 | + preferred_port is not None |
| 57 | + and preferred_port not in self._allocated_ports |
| 58 | + and self._is_port_free(preferred_port) |
| 59 | + ): |
| 60 | + self._allocated_ports.add(preferred_port) |
| 61 | + return preferred_port |
| 62 | + |
| 63 | + # Try to find a free port |
| 64 | + for attempt in range(max_attempts): |
| 65 | + port = self._find_free_port() |
| 66 | + |
| 67 | + # Double-check it's not in our reserved set (shouldn't happen, but be safe) |
| 68 | + if port not in self._allocated_ports: |
| 69 | + self._allocated_ports.add(port) |
| 70 | + return port |
| 71 | + |
| 72 | + raise RuntimeError( |
| 73 | + f"Failed to allocate a free port after {max_attempts} attempts. " |
| 74 | + f"Currently allocated ports: {len(self._allocated_ports)}" |
| 75 | + ) |
| 76 | + |
| 77 | + def release_port(self, port: int) -> None: |
| 78 | + """Release a previously allocated port. |
| 79 | +
|
| 80 | + Args: |
| 81 | + port: Port number to release |
| 82 | +
|
| 83 | + """ |
| 84 | + with self._lock: |
| 85 | + self._allocated_ports.discard(port) |
| 86 | + |
| 87 | + def release_all(self) -> None: |
| 88 | + """Release all allocated ports.""" |
| 89 | + with self._lock: |
| 90 | + self._allocated_ports.clear() |
| 91 | + |
| 92 | + @contextmanager |
| 93 | + def allocated_port(self, preferred_port: Optional[int] = None) -> Iterator[int]: |
| 94 | + """Context manager for automatic port cleanup. |
| 95 | +
|
| 96 | + Usage: |
| 97 | + with manager.allocated_port() as port: |
| 98 | + # Use port here |
| 99 | + pass |
| 100 | + # Port automatically released |
| 101 | +
|
| 102 | + Args: |
| 103 | + preferred_port: Optional preferred port number |
| 104 | +
|
| 105 | + Yields: |
| 106 | + Allocated port number |
| 107 | +
|
| 108 | + """ |
| 109 | + port = self.allocate_port(preferred_port=preferred_port) |
| 110 | + try: |
| 111 | + yield port |
| 112 | + finally: |
| 113 | + self.release_port(port) |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def _find_free_port() -> int: |
| 117 | + """Find a free port using OS allocation. |
| 118 | +
|
| 119 | + Returns: |
| 120 | + A port number that was free at the time of checking |
| 121 | +
|
| 122 | + """ |
| 123 | + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 124 | + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 125 | + s.bind(("", 0)) |
| 126 | + port = s.getsockname()[1] |
| 127 | + s.close() |
| 128 | + return port |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def _is_port_free(port: int) -> bool: |
| 132 | + """Check if a specific port is available. |
| 133 | +
|
| 134 | + Args: |
| 135 | + port: Port number to check |
| 136 | +
|
| 137 | + Returns: |
| 138 | + True if the port is free, False otherwise |
| 139 | +
|
| 140 | + """ |
| 141 | + try: |
| 142 | + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 143 | + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 144 | + s.bind(("", port)) |
| 145 | + s.close() |
| 146 | + return True |
| 147 | + except OSError: |
| 148 | + return False |
| 149 | + |
| 150 | + |
| 151 | +# Global singleton instance |
| 152 | +_port_manager: Optional[PortManager] = None |
| 153 | +_port_manager_lock = threading.Lock() |
| 154 | + |
| 155 | + |
| 156 | +def get_port_manager() -> PortManager: |
| 157 | + """Get or create the global port manager instance. |
| 158 | +
|
| 159 | + Returns: |
| 160 | + The global PortManager singleton |
| 161 | +
|
| 162 | + """ |
| 163 | + global _port_manager |
| 164 | + if _port_manager is None: |
| 165 | + with _port_manager_lock: |
| 166 | + if _port_manager is None: |
| 167 | + _port_manager = PortManager() |
| 168 | + return _port_manager |
0 commit comments