Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Hold allocated ports until the install claims them

Juan Denisc44da15993fa
diff --git a/backend/app/services/environment_docker_service.py b/backend/app/services/environment_docker_service.py
index d9936f6a..283304bb 100644
--- a/backend/app/services/environment_docker_service.py
+++ b/backend/app/services/environment_docker_service.py
@@ -452,7 +452,7 @@ networks:
@classmethod
def _find_available_port(cls) -> int:
"""Find an available port. Delegates to TemplateService."""
- return TemplateService._find_available_port()
+ return TemplateService._claim_port()
@classmethod
def _generate_password(cls, length: int = 32) -> str:
diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.py
index dd5537d7..5df7721d 100644
--- a/backend/app/services/template_service.py
+++ b/backend/app/services/template_service.py
@@ -30,6 +30,14 @@ import requests
from app import paths
from app.utils.system import app_process_env, run_checked
from app.services.deploy_lock import with_deploy_lock
+from app.exceptions import ConflictError
+
+# Ports handed to an install that has not written its app row (or started its
+# container) yet. Without this, two installs resolving a port variable at the
+# same time both saw the same port free. Single-process panel, so in-memory.
+_PORT_CLAIM_TTL = 15 * 60
+_claimed_ports = {}
+_claimed_ports_lock = threading.Lock()
class TemplateService:
@@ -624,7 +632,7 @@ class TemplateService:
base = cls._managed_app_base_port()
if base:
start_port = base
- return str(cls._find_available_port(start_port))
+ return str(cls._claim_port(start_port))
elif var_type == 'uuid':
import uuid
@@ -1047,7 +1055,7 @@ class TemplateService:
docker_ports = cls._get_docker_used_ports()
# Combine all used ports
- used_ports = db_ports | docker_ports
+ used_ports = db_ports | docker_ports | cls._live_claims()
for port in range(start_port, start_port + max_attempts):
# Skip reserved/common ports
@@ -1071,9 +1079,29 @@ class TemplateService:
except Exception:
continue
- # Fallback: return a random high port
- import random
- return random.randint(10000, 60000)
+ # A random port here could collide with anything; say so instead.
+ raise ConflictError(
+ f'No free port between {start_port} and {start_port + max_attempts - 1}')
+
+ @staticmethod
+ def _live_claims() -> set:
+ now = time.monotonic()
+ with _claimed_ports_lock:
+ for port, at in list(_claimed_ports.items()):
+ if now - at > _PORT_CLAIM_TTL:
+ del _claimed_ports[port]
+ return set(_claimed_ports)
+
+ @classmethod
+ def _claim_port(cls, start_port: int = 8000) -> int:
+ """Find a free port and hold it for the install about to use it."""
+ while True:
+ port = cls._find_available_port(start_port)
+ with _claimed_ports_lock:
+ if port not in _claimed_ports:
+ _claimed_ports[port] = time.monotonic()
+ return port
+ start_port = port + 1
@classmethod
def _port_is_free(cls, port) -> bool:
@@ -1087,7 +1115,8 @@ class TemplateService:
return False
if not 1 <= port <= 65535:
return False
- if port in (cls._get_database_used_ports() | cls._get_docker_used_ports()):
+ if port in (cls._get_database_used_ports() | cls._get_docker_used_ports()
+ | cls._live_claims()):
return False
try:
test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
diff --git a/backend/tests/test_port_claims.py b/backend/tests/test_port_claims.py
new file mode 100644
index 00000000..3a7b10bc
--- /dev/null
+++ b/backend/tests/test_port_claims.py
@@ -0,0 +1,60 @@
+"""Two installs resolving a port at once must not get the same port.
+
+The allocator only looked at app rows, containers and a bind test, none of
+which exist yet while an install is still being planned, so concurrent
+installs were handed the same port. When the range ran out it returned a
+random port that could collide with anything.
+"""
+import threading
+
+import pytest
+
+from app.exceptions import ConflictError
+from app.services import template_service
+from app.services.template_service import TemplateService
+
+
+def nothing_in_use(monkeypatch):
+ monkeypatch.setattr(TemplateService, '_get_database_used_ports', classmethod(lambda cls: set()))
+ monkeypatch.setattr(TemplateService, '_get_docker_used_ports', classmethod(lambda cls: set()))
+ monkeypatch.setattr(template_service, '_claimed_ports', {})
+
+
+def test_concurrent_claims_get_distinct_ports(nothing_in_use):
+ got, start = [], threading.Barrier(8)
+
+ def claim():
+ start.wait()
+ got.append(TemplateService._claim_port(41000))
+
+ threads = [threading.Thread(target=claim) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert len(got) == 8 and len(set(got)) == 8
+
+
+def test_claimed_port_is_not_suggested_or_free(nothing_in_use):
+ claimed = TemplateService._claim_port(41100)
+ assert TemplateService._find_available_port(41100) != claimed
+ assert TemplateService._port_is_free(claimed) is False
+
+
+def test_claims_expire(nothing_in_use, monkeypatch):
+ claimed = TemplateService._claim_port(41200)
+ monkeypatch.setattr(template_service, '_PORT_CLAIM_TTL', -1)
+ assert TemplateService._find_available_port(41200) == claimed
+
+
+def test_port_variable_resolution_claims(nothing_in_use):
+ first = TemplateService._claim_port(41300)
+ assert TemplateService._claim_port(41300) != first
+
+
+def test_exhausted_range_raises_instead_of_a_random_port(nothing_in_use, monkeypatch):
+ monkeypatch.setattr(TemplateService, '_get_database_used_ports',
+ classmethod(lambda cls: set(range(41400, 41410))))
+ with pytest.raises(ConflictError, match='No free port'):
+ TemplateService._find_available_port(41400, max_attempts=10)