|
27 | 27 | from requests.exceptions import ConnectionError, ConnectTimeout, ReadTimeout
|
28 | 28 | from urllib3.util.retry import Retry
|
29 | 29 |
|
| 30 | +from lightning_app.core import constants |
30 | 31 | from lightning_app.utilities.app_helpers import Logger
|
31 | 32 |
|
32 | 33 | logger = Logger(__name__)
|
33 | 34 |
|
34 | 35 |
|
| 36 | +# Global record to track ports that have been allocated in this session. |
| 37 | +_reserved_ports = set() |
| 38 | + |
| 39 | + |
35 | 40 | def find_free_network_port() -> int:
|
36 | 41 | """Finds a free port on localhost."""
|
37 |
| - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
38 |
| - s.bind(("", 0)) |
39 |
| - port = s.getsockname()[1] |
40 |
| - s.close() |
| 42 | + if constants.LIGHTNING_CLOUDSPACE_HOST is not None: |
| 43 | + return _find_free_network_port_cloudspace() |
| 44 | + |
| 45 | + port = None |
| 46 | + |
| 47 | + for _ in range(10): |
| 48 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 49 | + sock.bind(("", 0)) |
| 50 | + port = sock.getsockname()[1] |
| 51 | + sock.close() |
| 52 | + |
| 53 | + if port not in _reserved_ports: |
| 54 | + break |
| 55 | + |
| 56 | + if port in _reserved_ports: |
| 57 | + # Prevent an infinite loop, if we tried 10 times and didn't get a free port then something is wrong |
| 58 | + raise RuntimeError( |
| 59 | + "Couldn't find a free port. Please open an issue at `https://github.com/Lightning-AI/lightning/issues`." |
| 60 | + ) |
| 61 | + |
| 62 | + _reserved_ports.add(port) |
41 | 63 | return port
|
42 | 64 |
|
43 | 65 |
|
| 66 | +def _find_free_network_port_cloudspace(): |
| 67 | + """Finds a free port in the exposed range when running in a cloudspace.""" |
| 68 | + for port in range( |
| 69 | + constants.APP_SERVER_PORT, |
| 70 | + constants.APP_SERVER_PORT + constants.LIGHTNING_CLOUDSPACE_EXPOSED_PORT_COUNT, |
| 71 | + ): |
| 72 | + if port in _reserved_ports: |
| 73 | + continue |
| 74 | + |
| 75 | + try: |
| 76 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 77 | + sock.bind(("", port)) |
| 78 | + sock.close() |
| 79 | + _reserved_ports.add(port) |
| 80 | + return port |
| 81 | + except OSError: |
| 82 | + continue |
| 83 | + |
| 84 | + # This error should never happen. An app using this many ports would probably fail on a single machine anyway. |
| 85 | + raise RuntimeError(f"All {constants.LIGHTNING_CLOUDSPACE_EXPOSED_PORT_COUNT} ports are already in use.") |
| 86 | + |
| 87 | + |
44 | 88 | _CONNECTION_RETRY_TOTAL = 2880
|
45 | 89 | _CONNECTION_RETRY_BACKOFF_FACTOR = 0.5
|
46 | 90 | _DEFAULT_BACKOFF_MAX = 5 * 60 # seconds
|
|
0 commit comments