Skip to content

Commit 146e8e4

Browse files
committed
Pass the current docker context on to units and drivers as DOCKER_HOST
A unit's docker program and a driver run with a home of their own, so a Docker selected only by `docker context use` (kept in the user's ~/.docker/config.json) was not seen, and docker fell back to /var/run/docker.sock. Read the current context once with `docker context inspect` and pass its endpoint (and its TLS files) as DOCKER_HOST, DOCKER_CERT_PATH and DOCKER_TLS_VERIFY or DOCKER_TLS. DOCKER_HOST and DOCKER_CONTEXT, when set, still win. DOCKER_CONFIG is not passed: it would give the driver the user's registry logins.
1 parent e158751 commit 146e8e4

4 files changed

Lines changed: 67 additions & 2 deletions

File tree

‎app/nullius/standard/container.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@
9191
"""
9292
from __future__ import annotations
9393

94+
import functools
9495
import glob
9596
import hashlib
9697
import json
@@ -174,12 +175,40 @@ def _docker(args: List[str], *, env: Optional[dict] = None, input: Optional[str]
174175
def client_env(extra: Optional[dict] = None) -> dict:
175176
"""The docker program's environment: what it needs to find the daemon, and
176177
the values of the variables a ``-e NAME`` passes on."""
177-
env = {k: os.environ[k] for k in CLIENT_KEEP if k in os.environ}
178+
env = {**_context(), **{k: os.environ[k] for k in CLIENT_KEEP if k in os.environ}}
178179
env.setdefault("PATH", os.defpath)
179180
env.update(extra or {})
180181
return env
181182

182183

184+
@functools.cache
185+
def _context() -> Dict[str, str]:
186+
"""The daemon that ``docker context use`` selected, as the variables that
187+
name it. The user's ``~/.docker`` keeps that selection, and a unit or a
188+
driver has a home of its own. Only the endpoint goes on: the registry
189+
logins in ``~/.docker`` do not. Read once per process."""
190+
if os.environ.get("DOCKER_HOST") or os.environ.get("DOCKER_CONTEXT"):
191+
return {}
192+
try:
193+
r = subprocess.run([DOCKER, "context", "inspect"], capture_output=True, text=True, timeout=30)
194+
c = json.loads(r.stdout)[0]
195+
ep = c["Endpoints"]["docker"]
196+
except (OSError, subprocess.SubprocessError, ValueError, LookupError):
197+
return {}
198+
if c.get("Name") == "default":
199+
return {}
200+
env = {"DOCKER_HOST": ep["Host"]}
201+
tls = bool(c.get("TLSMaterial", {}).get("docker"))
202+
if tls:
203+
env["DOCKER_CERT_PATH"] = os.path.join(c["Storage"]["TLSPath"], "docker")
204+
# shortcut: docker reads a ca.pem from DOCKER_CERT_PATH, so a skip-verify context with a client certificate and no CA is not reached
205+
if ep.get("SkipTLSVerify"):
206+
env["DOCKER_TLS"] = "1"
207+
elif tls:
208+
env["DOCKER_TLS_VERIFY"] = "1"
209+
return env
210+
211+
183212
def unusable() -> Optional[str]:
184213
"""Why the container backend cannot run here, or None when it can."""
185214
try:

‎app/nullius/standard/run.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ def driver(self) -> jsonl.Proc:
493493
"NULLIUS_DATASET_ID": self.ds["id"], "PYTHONPATH": driver_path(), "PYTHONDONTWRITEBYTECODE": "1",
494494
"NULLIUS_VERSION": str(self.bench.get("_version") or ""),
495495
**({container.CHECK_IMAGE: self.image,
496-
**{k: os.environ[k] for k in container.CLIENT_KEEP if k.startswith("DOCKER") and k in os.environ}}
496+
**{k: v for k, v in container.client_env().items() if k.startswith("DOCKER")}}
497497
if self.image else {}),
498498
**option_env(getattr(self, "bench_options", {})), **self.embeddings_env(), **self.driver_secrets()})
499499
os.makedirs(env["HOME"], exist_ok=True)

‎app/tests/test_settings.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ def test_every_variable_the_application_reads_is_in_the_table(self):
3232
read -= {"NULLIUS_FORWARD_TO"} # a licence server's forwarder's, in its own container (standard/forward.py)
3333
read -= {"NULLIUS_MCP_AT"} # the MCP bridge's, in the agent's container (standard/mcp_bridge.py)
3434
read -= {"DOCKER_CONFIG"} # docker's own: where it keeps a login (sandbox.py reads the username)
35+
read -= {"DOCKER_HOST", "DOCKER_CONTEXT"} # docker's own: when set, container.py leaves the current context to them
3536
missing = sorted(v for v in read if v not in settings.BY_NAME and v not in settings.STARTUP)
3637
self.assertEqual(missing, [], f"read by the application but neither on the page nor a named start-up option: {missing}")
3738
self.assertEqual(sorted(set(settings.BY_NAME) & set(settings.STARTUP)), [])

‎app/tests/test_standard_container.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,41 @@ def test_missing_docker_is_said_plainly(self):
380380
self.assertEqual(container.unusable(), "docker is not installed on this machine")
381381

382382

383+
class ContextTest(unittest.TestCase):
384+
"""A Docker selected only by ``docker context use`` is in the user's
385+
``~/.docker``: the docker program still reaches it with a unit's home."""
386+
ALT = {"Name": "alt", "Endpoints": {"docker": {"Host": "unix:///run/alt.sock", "SkipTLSVerify": False}},
387+
"TLSMaterial": {}, "Storage": {"TLSPath": "/u/.docker/contexts/tls/abc"}}
388+
389+
def env(self, inspect: dict, **environ) -> dict:
390+
container._context.cache_clear()
391+
self.addCleanup(container._context.cache_clear)
392+
kept = {k: v for k, v in os.environ.items() if not k.startswith("DOCKER")}
393+
done = subprocess.CompletedProcess([], 0, json.dumps([inspect]), "")
394+
with mock.patch.dict(os.environ, {**kept, **environ}, clear=True), \
395+
mock.patch.object(container.subprocess, "run", return_value=done):
396+
return container.client_env({"HOME": "/unit-home"})
397+
398+
def test_the_current_context_is_passed_as_its_host(self):
399+
env = self.env(self.ALT)
400+
self.assertEqual((env["HOME"], env["DOCKER_HOST"]), ("/unit-home", "unix:///run/alt.sock"))
401+
self.assertNotIn("DOCKER_CONFIG", env) # not the user's logins
402+
self.assertNotIn("DOCKER_HOST", self.env(dict(self.ALT, Name="default")))
403+
404+
def test_docker_host_and_docker_context_win(self):
405+
self.assertEqual(self.env(self.ALT, DOCKER_HOST="tcp://h:2375")["DOCKER_HOST"], "tcp://h:2375")
406+
env = self.env(self.ALT, DOCKER_CONTEXT="other")
407+
self.assertEqual((env["DOCKER_CONTEXT"], env.get("DOCKER_HOST")), ("other", None))
408+
409+
def test_a_tls_context_passes_its_certificates(self):
410+
tls = dict(self.ALT, TLSMaterial={"docker": ["ca.pem", "cert.pem", "key.pem"]})
411+
env = self.env(tls)
412+
self.assertEqual((env["DOCKER_CERT_PATH"], env["DOCKER_TLS_VERIFY"]), ("/u/.docker/contexts/tls/abc/docker", "1"))
413+
tls["Endpoints"] = {"docker": {"Host": "tcp://h:2376", "SkipTLSVerify": True}}
414+
env = self.env(tls)
415+
self.assertEqual((env["DOCKER_TLS"], env.get("DOCKER_TLS_VERIFY")), ("1", None))
416+
417+
383418
def _ready() -> str:
384419
return docker_tier.why_not()
385420

0 commit comments

Comments
 (0)