diff --git a/backend/app/services/compose_network_service.py b/backend/app/services/compose_network_service.py new file mode 100644 index 00000000..a1a12333 --- /dev/null +++ b/backend/app/services/compose_network_service.py @@ -0,0 +1,232 @@ +"""Pinned subnets for compose projects once Docker's address pools run out. + +Every compose project gets its own bridge network, and Docker carves those out +of a fixed set of default pools: about thirty networks on a stock daemon. The +next ``compose up`` after that fails with "all predefined address pools have +been fully subnetted", which caps a host at roughly thirty stacks no matter how +much CPU, memory or disk is left. + +An explicit ``ipam`` subnet does not come out of the default pools, so the +project that hit the limit is given a small subnet of its own and started +again. The pin is written into the project's base compose file rather than a +ServerKit override: any ``compose up`` that left the pin out would recreate the +network from the exhausted pools and take the stack down with it. +""" +import ipaddress +import logging +import os +import tempfile +import threading +import time + +import yaml + +logger = logging.getLogger(__name__) + +POOL_ENV = 'SERVERKIT_COMPOSE_SUBNET_POOL' +DEFAULT_POOL = '10.213.0.0/16' +# 62 addresses: room for the largest bundled templates, 1024 projects per /16. +SUBNET_PREFIX = 26 + +_EXHAUSTED = ( + 'all predefined address pools have been fully subnetted', + 'could not find an available, non-overlapping ipv4 address pool', +) +_OVERLAP = 'pool overlaps with other one on this address space' + +# A subnet handed out here is not visible to `docker network inspect` until the +# retried `compose up` creates the network, so two deploys racing each other +# would be given the same one. Remember recent grants for that window. +_RECENT_TTL = 600 +_recent = {} +_lock = threading.Lock() + + +def needs_pinned_subnet(text): + """True when compose output says the project's network needs a pinned subnet.""" + lowered = (text or '').lower() + return _OVERLAP in lowered or any(marker in lowered for marker in _EXHAUSTED) + + +def _pool(): + raw = os.environ.get(POOL_ENV) or DEFAULT_POOL + try: + pool = ipaddress.ip_network(raw, strict=False) + if pool.version == 4 and pool.prefixlen <= SUBNET_PREFIX: + return pool + logger.warning('%s=%s is not an IPv4 network of /%s or larger; using %s', + POOL_ENV, raw, SUBNET_PREFIX, DEFAULT_POOL) + except ValueError: + logger.warning('%s=%s is not a network; using %s', POOL_ENV, raw, DEFAULT_POOL) + return ipaddress.ip_network(DEFAULT_POOL) + + +def _docker_subnets(): + """Subnets of every network the daemon knows about.""" + from app.services.docker_service import DockerService + listed = DockerService.run(['network', 'ls', '-q']) + ids = (listed.get('output') or '').split() + if not listed.get('success') or not ids: + return [] + inspected = DockerService.run( + ['network', 'inspect', '--format', '{{range .IPAM.Config}}{{.Subnet}} {{end}}', *ids]) + return (inspected.get('output') or '').split() + + +def _host_addresses(): + """The host's own IPv4 addresses, so a pin never lands on a live interface.""" + try: + import psutil + return [addr.address for addrs in psutil.net_if_addrs().values() + for addr in addrs if getattr(addr.family, 'name', '') == 'AF_INET'] + except Exception as exc: # noqa: BLE001 - a missing probe must not block the pin + logger.debug('host address probe failed: %s', exc) + return [] + + +def _taken(): + taken = [] + for raw in [*_docker_subnets(), *_host_addresses()]: + try: + taken.append(ipaddress.ip_network(raw, strict=False)) + except ValueError: + continue + now = time.monotonic() + for subnet, granted in list(_recent.items()): + if now - granted > _RECENT_TTL: + del _recent[subnet] + else: + taken.append(subnet) + return [net for net in taken if net.version == 4] + + +def _allocate(count): + """``count`` free subnets from the pool, or fewer if it is nearly full.""" + taken = _taken() + granted = [] + for candidate in _pool().subnets(new_prefix=SUBNET_PREFIX): + if len(granted) == count: + break + if any(candidate.overlaps(net) for net in taken): + continue + granted.append(candidate) + _recent[candidate] = time.monotonic() + return granted + + +def _ours(spec): + """True when a network's subnets were all pinned from our pool.""" + config = ((spec or {}).get('ipam') or {}).get('config') or [] + subnets = [entry.get('subnet') for entry in config if isinstance(entry, dict)] + if not subnets or not all(subnets): + return False + pool = _pool() + try: + return all(ipaddress.ip_network(s, strict=False).subnet_of(pool) for s in subnets) + except (ValueError, TypeError): + return False + + +def _networks_to_pin(config, repin): + """Names of the project's own bridge networks that draw on the default pools. + + ``repin`` also returns networks already pinned from our pool: a copied + project carries its source's subnet, which the daemon rejects as an overlap. + A subnet somebody chose themselves is never touched. + """ + services = config.get('services') or {} + networks = config.get('networks') or {} + names = [] + # A service that names no network (and has no network_mode) joins the + # implicit `default` one, which exists even when the file never declares it. + implicit_default = any( + isinstance(svc, dict) and not svc.get('network_mode') + and (not svc.get('networks') or 'default' in svc['networks']) + for svc in services.values()) + if implicit_default and 'default' not in networks: + names.append('default') + for name, spec in networks.items(): + spec = spec or {} + if not isinstance(spec, dict) or spec.get('external'): + continue + if spec.get('driver') not in (None, 'bridge'): + continue + has_subnet = bool((spec.get('ipam') or {}).get('config')) + if not has_subnet or (repin and _ours(spec)): + names.append(name) + return names + + +def _replace(path, content): + """Same-directory atomic replacement; never leave a half-written compose.""" + directory = os.path.dirname(path) + fd, temporary = tempfile.mkstemp(dir=directory, prefix='.network-pin-') + try: + with os.fdopen(fd, 'w', encoding='utf-8') as stream: + stream.write(content) + if os.name != 'nt': + os.chmod(temporary, os.stat(path).st_mode & 0o777) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def pin_project_subnets(project_path, compose_file=None, error_text=''): + """Give a compose project's networks subnets outside Docker's default pools. + + Returns ``{'success': bool, 'pinned': {network: subnet}, 'error': str|None}``. + Never raises: this runs on a deploy's failure path, where a second + exception would bury the daemon's own message. + """ + try: + with _lock: + return _pin(project_path, compose_file, error_text) + except Exception as exc: # noqa: BLE001 - see docstring + logger.warning('could not pin compose subnets for %s: %s', project_path, exc) + return {'success': False, 'pinned': {}, 'error': str(exc)} + + +def _pin(project_path, compose_file, error_text): + from app.services.compose_env_service import ComposeEnvService + base = ComposeEnvService.find_base_compose(project_path, compose_file) + if not base: + return {'success': False, 'pinned': {}, 'error': 'no compose file found'} + path = base if os.path.isabs(base) else os.path.join(project_path, base) + with open(path, 'r', encoding='utf-8') as stream: + original = stream.read() + config = yaml.safe_load(original) or {} + if not isinstance(config, dict): + return {'success': False, 'pinned': {}, 'error': 'compose file is not a mapping'} + + names = _networks_to_pin(config, repin=_OVERLAP in (error_text or '').lower()) + if not names: + return {'success': False, 'pinned': {}, + 'error': 'no project network draws on the default address pools'} + subnets = _allocate(len(names)) + if len(subnets) < len(names): + return {'success': False, 'pinned': {}, + 'error': f'subnet pool {_pool()} is full; set {POOL_ENV} to a larger network'} + pinned = {name: str(subnet) for name, subnet in zip(names, subnets)} + + if 'networks' not in config: + # The common shape (one implicit network): append, so the rest of the + # file keeps its comments and formatting. + block = yaml.safe_dump( + {'networks': {name: {'ipam': {'config': [{'subnet': subnet}]}} + for name, subnet in pinned.items()}}, + default_flow_style=False, sort_keys=False) + content = (original.rstrip('\n') + '\n\n' + "# Pinned by ServerKit: Docker's default address pools were full.\n" + + block) + else: + networks = config['networks'] or {} + for name, subnet in pinned.items(): + spec = networks.get(name) or {} + spec['ipam'] = {**(spec.get('ipam') or {}), 'config': [{'subnet': subnet}]} + networks[name] = spec + config['networks'] = networks + content = yaml.safe_dump(config, default_flow_style=False, sort_keys=False) + _replace(path, content) + logger.info('pinned compose subnets for %s: %s', project_path, pinned) + return {'success': True, 'pinned': pinned, 'error': None} diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py index 5684b07e..3350e707 100644 --- a/backend/app/services/docker_service.py +++ b/backend/app/services/docker_service.py @@ -5,6 +5,7 @@ import json import os import shlex import yaml +from collections import deque from datetime import datetime from app.exceptions import DependencyUnavailableError @@ -1165,12 +1166,44 @@ class DockerService: cmd.append('--build') result = cls.run_compose(cmd, cwd=project_path) + if not result['success'] and cls._pin_subnets_on_pool_error( + project_path, compose_file, + ' '.join(str(result.get(k) or '') for k in ('error', 'stderr', 'output'))): + result = cls.run_compose(cmd, cwd=project_path) if result['success']: return {'success': True, 'output': result['output']} return {'success': False, 'error': result['error'], 'output': result['output']} except Exception as e: return {'success': False, 'error': str(e)} + @staticmethod + def _pin_subnets_on_pool_error(project_path, compose_file, text, on_line=None): + """Pin the project's networks when ``compose up`` failed because + Docker's default address pools are full. True means "retry the up". + + A stock daemon has room for about thirty compose networks; past that + every new stack fails at network creation however idle the host is. + """ + from app.services import compose_network_service + if not compose_network_service.needs_pinned_subnet(text): + return False + result = compose_network_service.pin_project_subnets( + project_path, compose_file, error_text=text) + if result['success']: + pins = ', '.join(f'{name} -> {subnet}' for name, subnet in result['pinned'].items()) + note = ("ServerKit: Docker's default address pools are full; " + f'pinned a dedicated subnet ({pins}) and retrying.') + else: + note = ("ServerKit: Docker's default address pools are full and no " + f"subnet could be pinned: {result['error']}") + logger.warning('%s (%s)', note, project_path) + if on_line: + try: + on_line(note) + except Exception: + pass + return result['success'] + @classmethod def compose_up_streaming(cls, project_path, on_line, detach=True, build=False, compose_file=None): @@ -1205,18 +1238,28 @@ class DockerService: if build: cmd.append('--build') - proc = subprocess.Popen( - cmd, cwd=project_path, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - text=True, bufsize=1, - ) - for line in iter(proc.stdout.readline, ''): - try: - on_line(line.rstrip('\n')) - except Exception: - pass - proc.stdout.close() - exit_code = proc.wait() + def _run(): + proc = subprocess.Popen( + cmd, cwd=project_path, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, bufsize=1, + ) + # The tail is enough to recognise a network failure, and a + # build can print megabytes before it gets there. + transcript = deque(maxlen=200) + for line in iter(proc.stdout.readline, ''): + transcript.append(line) + try: + on_line(line.rstrip('\n')) + except Exception: + pass + proc.stdout.close() + return proc.wait(), ''.join(transcript) + + exit_code, transcript = _run() + if exit_code != 0 and cls._pin_subnets_on_pool_error( + project_path, compose_file, transcript, on_line=on_line): + exit_code, _ = _run() return {'success': exit_code == 0, 'exit_code': exit_code} except Exception as e: try: diff --git a/backend/tests/test_compose_network_pool.py b/backend/tests/test_compose_network_pool.py new file mode 100644 index 00000000..a0363a58 --- /dev/null +++ b/backend/tests/test_compose_network_pool.py @@ -0,0 +1,254 @@ +"""A host must not stop at ~30 compose stacks. + +Issue #254: creating one more WordPress site failed with "all predefined +address pools have been fully subnetted". Every compose project takes a bridge +network from Docker's default pools, a stock daemon has about thirty of them, +and nothing in the panel knew the limit existed. + +``compose up`` now answers that failure by pinning the project's networks to +subnets outside the default pools and starting again. +""" + +import ipaddress + +import pytest +import yaml + +from app.services import compose_network_service as cns +from app.services.docker_service import DockerService + +EXHAUSTED = ('failed to create network site_default: Error response from daemon: ' + 'all predefined address pools have been fully subnetted') +OVERLAP = ('failed to create network site_default: Error response from daemon: ' + 'invalid pool request: Pool overlaps with other one on this address space') + + +@pytest.fixture(autouse=True) +def _isolated_allocator(monkeypatch): + cns._recent.clear() + monkeypatch.delenv(cns.POOL_ENV, raising=False) + monkeypatch.setattr(cns, '_docker_subnets', lambda: []) + monkeypatch.setattr(cns, '_host_addresses', lambda: []) + yield + cns._recent.clear() + + +def _project(tmp_path, text): + (tmp_path / 'docker-compose.yml').write_text(text, encoding='utf-8') + return str(tmp_path) + + +def _compose(path): + with open(f'{path}/docker-compose.yml', encoding='utf-8') as stream: + return yaml.safe_load(stream) + + +def _subnet(config, network='default'): + return config['networks'][network]['ipam']['config'][0]['subnet'] + + +SIMPLE = '''# kept: a comment the pin must not eat +services: + wordpress: + image: wordpress + ports: + - "8300:80" + db: + image: mysql:8.4 +''' + + +class TestDetection: + @pytest.mark.parametrize('text', [ + EXHAUSTED, + 'could not find an available, non-overlapping IPv4 address pool among ' + 'the defaults to assign to the network', + OVERLAP, + ]) + def test_daemon_messages_are_recognised(self, text): + assert cns.needs_pinned_subnet(text) + + @pytest.mark.parametrize('text', [None, '', 'pull access denied for wordpress', + 'port is already allocated']) + def test_other_failures_are_left_alone(self, text): + assert not cns.needs_pinned_subnet(text) + + +class TestPin: + def test_implicit_default_network_is_pinned_and_file_kept(self, tmp_path): + path = _project(tmp_path, SIMPLE) + result = cns.pin_project_subnets(path, error_text=EXHAUSTED) + + assert result['success'] and list(result['pinned']) == ['default'] + text = (tmp_path / 'docker-compose.yml').read_text(encoding='utf-8') + assert text.startswith(SIMPLE) # appended, not rewritten + subnet = ipaddress.ip_network(_subnet(_compose(path))) + assert subnet.subnet_of(ipaddress.ip_network(cns.DEFAULT_POOL)) + assert subnet.prefixlen == cns.SUBNET_PREFIX + assert _compose(path)['services']['wordpress']['ports'] == ['8300:80'] + + def test_skips_subnets_docker_and_the_host_already_use(self, tmp_path, monkeypatch): + monkeypatch.setattr(cns, '_docker_subnets', lambda: ['10.213.0.0/24']) + monkeypatch.setattr(cns, '_host_addresses', lambda: ['10.213.1.5']) + path = _project(tmp_path, SIMPLE) + cns.pin_project_subnets(path, error_text=EXHAUSTED) + + subnet = ipaddress.ip_network(_subnet(_compose(path))) + assert not subnet.overlaps(ipaddress.ip_network('10.213.0.0/24')) + assert ipaddress.ip_address('10.213.1.5') not in subnet + assert str(subnet) == '10.213.1.64/26' + + def test_two_projects_before_either_network_exists_differ(self, tmp_path): + # Neither subnet is visible to the daemon until the retried `up` runs. + (tmp_path / 'a').mkdir() + (tmp_path / 'b').mkdir() + first = _project(tmp_path / 'a', SIMPLE) + second = _project(tmp_path / 'b', SIMPLE) + cns.pin_project_subnets(first, error_text=EXHAUSTED) + cns.pin_project_subnets(second, error_text=EXHAUSTED) + assert _subnet(_compose(first)) != _subnet(_compose(second)) + + def test_declared_networks_are_pinned_external_and_chosen_ones_are_not(self, tmp_path): + path = _project(tmp_path, '''services: + web: + image: nginx + networks: [front, shared, fixed, overlay] +networks: + front: + shared: + external: true + fixed: + ipam: + config: + - subnet: 172.30.9.0/24 + overlay: + driver: overlay +''') + result = cns.pin_project_subnets(path, error_text=EXHAUSTED) + + assert list(result['pinned']) == ['front'] + networks = _compose(path)['networks'] + assert networks['shared'] == {'external': True} + assert _subnet(_compose(path), 'fixed') == '172.30.9.0/24' + assert networks['overlay'] == {'driver': 'overlay'} + + def test_a_copied_pin_is_replaced_only_on_an_overlap(self, tmp_path): + path = _project(tmp_path, SIMPLE) + cns.pin_project_subnets(path, error_text=EXHAUSTED) + copied = _subnet(_compose(path)) + + # Exhaustion elsewhere is not about a network that already has a subnet. + assert not cns.pin_project_subnets(path, error_text=EXHAUSTED)['success'] + assert _subnet(_compose(path)) == copied + + # The copy's source still holds the subnet. + assert cns.pin_project_subnets(path, error_text=OVERLAP)['success'] + assert _subnet(_compose(path)) != copied + + def test_a_subnet_someone_chose_is_never_replaced(self, tmp_path): + path = _project(tmp_path, '''services: + web: + image: nginx +networks: + default: + ipam: + config: + - subnet: 172.30.9.0/24 +''') + assert not cns.pin_project_subnets(path, error_text=OVERLAP)['success'] + assert _subnet(_compose(path)) == '172.30.9.0/24' + + def test_host_networked_project_has_nothing_to_pin(self, tmp_path): + path = _project(tmp_path, 'services:\n web:\n image: nginx\n network_mode: host\n') + result = cns.pin_project_subnets(path, error_text=EXHAUSTED) + assert not result['success'] and 'networks' not in _compose(path) + + def test_full_pool_says_so(self, tmp_path, monkeypatch): + monkeypatch.setenv(cns.POOL_ENV, '10.213.0.0/26') + monkeypatch.setattr(cns, '_docker_subnets', lambda: ['10.213.0.0/26']) + result = cns.pin_project_subnets(_project(tmp_path, SIMPLE), error_text=EXHAUSTED) + assert not result['success'] and cns.POOL_ENV in result['error'] + + def test_pool_is_configurable(self, tmp_path, monkeypatch): + monkeypatch.setenv(cns.POOL_ENV, '192.168.200.0/24') + path = _project(tmp_path, SIMPLE) + cns.pin_project_subnets(path, error_text=EXHAUSTED) + assert _subnet(_compose(path)) == '192.168.200.0/26' + + def test_missing_compose_file_never_raises(self, tmp_path): + assert not cns.pin_project_subnets(str(tmp_path), error_text=EXHAUSTED)['success'] + + +class TestComposeUpRetries: + @pytest.fixture(autouse=True) + def _plain_command(self, monkeypatch): + monkeypatch.setattr(DockerService, '_compose_cmd_with_overlay', + classmethod(lambda cls, path, compose_file=None: + ['docker', 'compose'])) + + def test_exhausted_pool_is_pinned_and_retried(self, tmp_path, monkeypatch): + path = _project(tmp_path, SIMPLE) + calls = [] + + def run_compose(cmd, cwd=None, timeout=None): + calls.append(cmd) + if len(calls) == 1: + return {'success': False, 'output': '', 'stderr': EXHAUSTED, + 'error': EXHAUSTED, 'returncode': 1} + return {'success': True, 'output': 'started', 'stderr': '', + 'error': None, 'returncode': 0} + + monkeypatch.setattr(DockerService, 'run_compose', staticmethod(run_compose)) + result = DockerService.compose_up(path) + + assert result == {'success': True, 'output': 'started'} + assert len(calls) == 2 + assert _subnet(_compose(path)) + + def test_other_failures_are_not_retried(self, tmp_path, monkeypatch): + path = _project(tmp_path, SIMPLE) + calls = [] + + def run_compose(cmd, cwd=None, timeout=None): + calls.append(cmd) + return {'success': False, 'output': '', 'stderr': 'port is already allocated', + 'error': 'port is already allocated', 'returncode': 1} + + monkeypatch.setattr(DockerService, 'run_compose', staticmethod(run_compose)) + result = DockerService.compose_up(path) + + assert not result['success'] and len(calls) == 1 + assert 'networks' not in _compose(path) + + def test_streaming_up_pins_retries_and_says_what_it_did(self, tmp_path, monkeypatch): + path = _project(tmp_path, SIMPLE) + runs = [] + + class _Stdout: + def __init__(self, lines): + self._lines = iter(lines) + + def readline(self): + return next(self._lines, '') + + def close(self): + pass + + class _Proc: + def __init__(self, cmd, **kwargs): + runs.append(cmd) + self._code = 1 if len(runs) == 1 else 0 + self.stdout = _Stdout([EXHAUSTED + '\n'] if self._code else ['started\n']) + + def wait(self): + return self._code + + monkeypatch.setattr('subprocess.Popen', _Proc) + monkeypatch.setattr(DockerService, '_is_compose_v2', classmethod(lambda cls: True)) + lines = [] + result = DockerService.compose_up_streaming(path, lines.append) + + assert result == {'success': True, 'exit_code': 0} + assert len(runs) == 2 + assert any('pinned a dedicated subnet (default -> 10.213.' in line for line in lines) + assert lines[-1] == 'started' diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 8e6b65ae..839aecba 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -37,6 +37,7 @@ variable that is not listed here. | `SITES_BASE_DOMAIN` | empty (`lvh.me` in development) | Managed sites are published at `.`. Empty falls back to `localhost:` URLs. The panel setting overrides it. | | `SERVER_PUBLIC_IP` | empty | IP that auto-created DNS records point at. | | `SERVERKIT_ALLOW_PRIVATE_WEBHOOKS` | off | Let outgoing webhooks and event subscriptions reach private/internal addresses (the SSRF guard blocks them by default). | +| `SERVERKIT_COMPOSE_SUBNET_POOL` | `10.213.0.0/16` | Where an app's Docker network gets its subnet once Docker's own address pools are full (about thirty stacks on a stock daemon). Each app takes a `/26`; change it if the range is routed elsewhere on your network. | ## Security and secrets