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.

refactor(docker): one runner behind the private wrappers

Juan Denisa7350b7a7bb1
diff --git a/backend/app/services/db_admin_sso_service.py b/backend/app/services/db_admin_sso_service.py
index 2da6da29..f04f5575 100644
--- a/backend/app/services/db_admin_sso_service.py
+++ b/backend/app/services/db_admin_sso_service.py
@@ -15,9 +15,10 @@ minutes. All docker interaction funnels through the single choke-point
import logging
import os
import secrets
-import subprocess
from datetime import datetime, timedelta
+from app.services.docker_service import DockerService
+
logger = logging.getLogger(__name__)
SHADOW_TTL_MINUTES = 5
@@ -45,28 +46,16 @@ class DbAdminSsoService:
# ── choke-point: ALL docker interaction goes through here (tests stub it) ──
@classmethod
def _docker(cls, args, timeout=60):
- """Run ``docker <args>``; returns {'success', 'output', 'error'}."""
- try:
- result = subprocess.run(['docker'] + list(args),
- capture_output=True, text=True, timeout=timeout)
- return {
- 'success': result.returncode == 0,
- 'output': result.stdout,
- 'error': result.stderr if result.returncode != 0 else None,
- }
- except FileNotFoundError:
- return {'success': False, 'error': 'Docker not found'}
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Docker command timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ """Run ``docker <args>`` — via DockerService.run (§G3).
+
+ The named seam stays because this service's tests stub it; the wrapper
+ body does not.
+ """
+ return DockerService.run(args, timeout=timeout)
@classmethod
def _docker_available(cls):
- if os.name == 'nt':
- return False
- return cls._docker(['version', '--format', '{{.Server.Version}}'],
- timeout=10).get('success', False)
+ return DockerService.available()
# ── Adminer container lifecycle ──
@classmethod
diff --git a/backend/app/services/db_config_tuner_service.py b/backend/app/services/db_config_tuner_service.py
index 3c1f3b4b..352d27d6 100644
--- a/backend/app/services/db_config_tuner_service.py
+++ b/backend/app/services/db_config_tuner_service.py
@@ -145,19 +145,14 @@ class DbConfigTunerService:
@classmethod
def _docker(cls, args, timeout=60):
- """Run a docker CLI command. Single shell choke point."""
- import subprocess
- try:
- result = subprocess.run(['docker'] + list(args),
- capture_output=True, text=True, timeout=timeout)
- return {
- 'success': result.returncode == 0,
- 'output': result.stdout,
- 'error': (result.stderr.strip() or 'docker command failed')
- if result.returncode != 0 else None,
- }
- except Exception as e:
- return {'success': False, 'output': '', 'error': str(e)}
+ """Run a docker CLI command — via DockerService.run (§G3).
+
+ The named seam stays (tests stub it). The private copy collapsed a
+ missing docker and a timed-out docker into the same ``str(e)``, so a
+ caller could not tell "not installed" from "too slow".
+ """
+ from app.services.docker_service import DockerService
+ return DockerService.run(args, timeout=timeout)
@classmethod
def _exec_sql(cls, target, sql):
diff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.py
index 8da5cfc0..0b110d6c 100644
--- a/backend/app/services/docker_service.py
+++ b/backend/app/services/docker_service.py
@@ -48,6 +48,55 @@ class DockerService:
"""
return cls._get_compose_cmd() == ['docker', 'compose']
+ @staticmethod
+ def run(args, timeout=60):
+ """Run ``docker <args>``; one result shape for every caller (§G3).
+
+ Three services kept private ``_docker()`` wrappers around this exact
+ call, and the three had already drifted into three *different* return
+ contracts: one dict that mapped FileNotFoundError to "Docker not
+ found", one dict that collapsed every failure into ``str(e)``, and one
+ that handed back a raw ``CompletedProcess``. A caller reading
+ ``result['success']`` against the third silently got a ``KeyError``
+ rather than an answer.
+
+ Returns ``{'success': bool, 'output': str, 'error': str|None}``.
+ ``error`` distinguishes the three things that are not "the command said
+ no": docker absent, docker too slow, and everything else. A caller that
+ cannot tell those apart is the caller that reports "not installed"
+ because a probe timed out (§A).
+ """
+ try:
+ result = subprocess.run(['docker', *args], capture_output=True,
+ text=True, timeout=timeout)
+ except FileNotFoundError:
+ return {'success': False, 'output': '', 'error': 'Docker not found'}
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'output': '',
+ 'error': f'Docker command timed out after {timeout}s'}
+ except Exception as e: # noqa: BLE001
+ return {'success': False, 'output': '', 'error': str(e)}
+ return {
+ 'success': result.returncode == 0,
+ 'output': result.stdout or '',
+ 'error': ((result.stderr or '').strip() or 'docker command failed')
+ if result.returncode != 0 else None,
+ }
+
+ @classmethod
+ def available(cls):
+ """True when the docker daemon answers. Never raises.
+
+ Asks the daemon, not just the binary: ``docker version --format
+ {{.Server.Version}}`` fails when the CLI is installed but the daemon is
+ down, which is the state a "docker is available" check actually cares
+ about.
+ """
+ if os.name == 'nt':
+ return False
+ return cls.run(['version', '--format', '{{.Server.Version}}'],
+ timeout=10)['success']
+
@staticmethod
def is_docker_installed():
"""Check if Docker is installed and running."""
diff --git a/backend/app/services/image_update_service.py b/backend/app/services/image_update_service.py
index 886d4f48..e3a39232 100644
--- a/backend/app/services/image_update_service.py
+++ b/backend/app/services/image_update_service.py
@@ -2,12 +2,12 @@
by comparing the locally-present digest with the registry's current digest for
the same tag. Shells out to `docker` like the rest of the Docker layer."""
import logging
-import subprocess
from datetime import datetime
from app import db
from app.models import Application
from app.models.image_update import ImageUpdateCheck
+from app.services.docker_service import DockerService
logger = logging.getLogger(__name__)
@@ -16,36 +16,37 @@ class ImageUpdateService:
@staticmethod
def _docker(args, timeout=60):
- return subprocess.run(['docker', *args], capture_output=True, text=True, timeout=timeout)
+ """Run ``docker <args>`` — via DockerService.run (§G3).
+
+ The seam stays (tests stub it), but the result shape is now the one
+ every other docker caller gets. This wrapper used to hand back a raw
+ ``CompletedProcess`` while the two other private ``_docker`` wrappers
+ returned dicts — three names, three contracts.
+ """
+ return DockerService.run(args, timeout=timeout)
@classmethod
def _local_digest(cls, image_ref):
"""RepoDigest (sha256:...) of the locally-present image, or None when the
image isn't pulled or was built locally (no registry digest)."""
- try:
- result = cls._docker(['image', 'inspect', image_ref, '--format', '{{index .RepoDigests 0}}'])
- if result.returncode != 0:
- return None
- out = result.stdout.strip()
- return out.split('@', 1)[1].strip() if '@sha256:' in out else None
- except Exception:
+ result = cls._docker(['image', 'inspect', image_ref, '--format', '{{index .RepoDigests 0}}'])
+ if not result['success']:
return None
+ out = result['output'].strip()
+ return out.split('@', 1)[1].strip() if '@sha256:' in out else None
@classmethod
def _registry_digest(cls, image_ref):
"""Current index digest (sha256:...) for the ref's tag in its registry,
or None when the registry is unreachable or buildx is unavailable."""
- try:
- result = cls._docker(
- ['buildx', 'imagetools', 'inspect', image_ref, '--format', '{{.Manifest.Digest}}'],
- timeout=30,
- )
- if result.returncode != 0:
- return None
- out = result.stdout.strip()
- return out if out.startswith('sha256:') else None
- except Exception:
+ result = cls._docker(
+ ['buildx', 'imagetools', 'inspect', image_ref, '--format', '{{.Manifest.Digest}}'],
+ timeout=30,
+ )
+ if not result['success']:
return None
+ out = result['output'].strip()
+ return out if out.startswith('sha256:') else None
@classmethod
def check_application(cls, application_id):
diff --git a/backend/tests/test_docker_runner.py b/backend/tests/test_docker_runner.py
new file mode 100644
index 00000000..d6d02b3f
--- /dev/null
+++ b/backend/tests/test_docker_runner.py
@@ -0,0 +1,114 @@
+"""The one docker runner (plan 75 §G3).
+
+Three services kept private `_docker()` wrappers around the same
+`subprocess.run(['docker', ...])` call, and the three had drifted into three
+different return contracts — two dict shapes that disagreed about error text,
+and one that handed back a raw `CompletedProcess`. A caller reading
+`result['success']` against the third got a TypeError, not an answer.
+
+What each copy half-did is asserted here once, with particular attention to the
+distinctions §A says a probe must keep: "docker said no", "docker is absent",
+and "docker did not answer in time" are three different facts.
+"""
+
+import subprocess
+
+import pytest
+
+from app.services.docker_service import DockerService
+
+
+class TestResultShape:
+ def test_success_carries_stdout(self, fake_subprocess):
+ fake_subprocess.script(['docker', 'ps'], stdout='CONTAINER\n')
+ assert DockerService.run(['ps']) == {
+ 'success': True, 'output': 'CONTAINER\n', 'error': None}
+
+ def test_failure_carries_stderr(self, fake_subprocess):
+ fake_subprocess.script(['docker'], returncode=1, stderr='No such container\n')
+ result = DockerService.run(['inspect', 'nope'])
+ assert result['success'] is False
+ assert result['error'] == 'No such container'
+
+ def test_failure_with_empty_stderr_still_has_an_error_string(self, fake_subprocess):
+ """One of the three copies returned error=None here, so a caller that
+ rendered result['error'] showed the operator nothing at all."""
+ fake_subprocess.script(['docker'], returncode=1, stderr='')
+ result = DockerService.run(['ps'])
+ assert result['success'] is False
+ assert result['error']
+
+ def test_output_is_a_string_even_on_failure(self, fake_subprocess):
+ fake_subprocess.script(['docker'], returncode=1, stderr='boom')
+ assert DockerService.run(['ps'])['output'] == ''
+
+
+class TestTheThreeWaysItCanNotWork:
+ """The distinctions the drifted copies collapsed."""
+
+ def test_docker_absent_says_so(self, fake_subprocess):
+ fake_subprocess.script(['docker'], raises=FileNotFoundError)
+ result = DockerService.run(['ps'])
+ assert result['success'] is False
+ assert 'not found' in result['error'].lower()
+
+ def test_timeout_says_so_and_names_the_limit(self, fake_subprocess):
+ fake_subprocess.script(['docker'],
+ raises=subprocess.TimeoutExpired('docker', 60))
+ result = DockerService.run(['ps'], timeout=60)
+ assert result['success'] is False
+ assert 'timed out' in result['error']
+ assert '60' in result['error']
+
+ def test_absent_and_timed_out_are_distinguishable(self, fake_subprocess):
+ """db_config_tuner's copy collapsed both into str(e), so the caller
+ could not tell "install docker" from "the daemon is wedged"."""
+ fake_subprocess.script(['docker'], raises=FileNotFoundError)
+ absent = DockerService.run(['ps'])['error']
+ fake_subprocess.script(['docker'],
+ raises=subprocess.TimeoutExpired('docker', 5))
+ slow = DockerService.run(['ps'], timeout=5)['error']
+ assert absent != slow
+
+
+class TestAvailable:
+ def test_asks_the_daemon_not_just_the_binary(self, fake_subprocess, monkeypatch):
+ """`docker version --format {{.Server.Version}}` fails when the CLI is
+ installed but the daemon is down — the state callers care about."""
+ monkeypatch.setattr('app.services.docker_service.os.name', 'posix')
+ fake_subprocess.script(['docker', 'version'], stdout='27.0.3\n')
+ assert DockerService.available() is True
+ assert '{{.Server.Version}}' in fake_subprocess.argv_for(['docker', 'version'])
+
+ def test_daemon_down_is_false(self, fake_subprocess, monkeypatch):
+ monkeypatch.setattr('app.services.docker_service.os.name', 'posix')
+ fake_subprocess.script(['docker'], returncode=1, stderr='Cannot connect')
+ assert DockerService.available() is False
+
+ def test_missing_docker_is_false_not_an_exception(self, fake_subprocess, monkeypatch):
+ monkeypatch.setattr('app.services.docker_service.os.name', 'posix')
+ fake_subprocess.script(['docker'], raises=FileNotFoundError)
+ assert DockerService.available() is False
+
+ def test_windows_is_false_without_running_anything(self, fake_subprocess, monkeypatch):
+ monkeypatch.setattr('app.services.docker_service.os.name', 'nt')
+ assert DockerService.available() is False
+ assert fake_subprocess.commands() == []
+
+
+class TestTheWrappersDelegate:
+ """The three private copies are gone; the named seams remain."""
+
+ @pytest.mark.parametrize('module_path,attr', [
+ ('app.services.db_admin_sso_service', 'DbAdminSsoService'),
+ ('app.services.db_config_tuner_service', 'DbConfigTunerService'),
+ ('app.services.image_update_service', 'ImageUpdateService'),
+ ])
+ def test_every_wrapper_returns_the_shared_shape(self, module_path, attr,
+ fake_subprocess):
+ import importlib
+ service = getattr(importlib.import_module(module_path), attr)
+ fake_subprocess.script(['docker'], stdout='ok\n')
+ result = service._docker(['ps'])
+ assert set(result) == {'success', 'output', 'error'}
+ assert result['success'] is True and result['output'] == 'ok\n'