Debian Codegraph @

src/briefcase/integrations/docker.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import os
5 import socket
6 import subprocess
7 import sys
8 from collections.abc import Iterable, Mapping
9 from functools import cache
10 from pathlib import Path, PosixPath, PurePosixPath
11
12 from packaging.version import InvalidVersion, Version
13
14 from briefcase.config import AppConfig
15 from briefcase.exceptions import BriefcaseCommandError
16 from briefcase.integrations.base import Tool, ToolCache
17 from briefcase.integrations.subprocess import SubprocessArgsT
18
19
20 class XauthDatabaseCreationFailure(Exception):
21 """Creating a xauth database file from the user's current X auth failed."""
22
23
24 class Docker(Tool):
25 name = "docker"
26 full_name = "Docker"
27
28 DOCKER_VERSION_MIN = "20.10"
29
30 WRONG_DOCKER_VERSION_ERROR = """\
31 Briefcase requires Docker {version_min} or higher, but you are currently running
32 version {docker_version}. Visit:
33
34 {install_url}
35
36 to download and install an updated version of Docker.
37 """
38 UNKNOWN_DOCKER_VERSION_WARNING = """
39 *************************************************************************
40 ** WARNING: Unable to determine the version of Docker **
41 *************************************************************************
42
43 Briefcase will proceed, assuming everything is OK. If you
44 experience problems, this is almost certainly the cause of those
45 problems.
46
47 Please report this as a bug at:
48
49 https://github.com/beeware/briefcase/issues/new
50
51 In your report, please including the output from running:
52
53 $ docker --version
54
55 from the command prompt.
56
57 *************************************************************************
58 """
59 DOCKER_INSTALLATION_STATUS_UNKNOWN_WARNING = """
60 *************************************************************************
61 ** WARNING: Unable to determine if Docker is installed **
62 *************************************************************************
63
64 Briefcase will proceed, assuming everything is OK. If you
65 experience problems, this is almost certainly the cause of those
66 problems.
67
68 Please report this as a bug at:
69
70 https://github.com/beeware/briefcase/issues/new
71
72 In your report, please including the output from running:
73
74 $ docker --version
75
76 from the command prompt.
77
78 *************************************************************************
79 """
80 DOCKER_NOT_INSTALLED_ERROR = """\
81 Briefcase requires Docker, but it is not installed (or is not on your PATH).
82 Visit:
83
84 {install_url}
85
86 to download and install Docker manually.
87
88 If you have installed Docker recently and are still getting this error, you may
89 need to restart your terminal session.
90 """
91
92 LACKS_PERMISSION_ERROR = """\
93 Docker has been installed, but Briefcase is unable to invoke
94 Docker commands. It is possible that your user does not have
95 permissions to invoke Docker.
96
97 See https://docs.docker.com/engine/install/linux-postinstall/
98 for details on configuring access to your Docker installation.
99 """
100 DAEMON_NOT_RUNNING_ERROR = """\
101 Briefcase is unable to use Docker commands. It appears the Docker
102 daemon is not running.
103
104 See https://docs.docker.com/config/daemon/ for details on how to
105 configure your Docker daemon.
106 """
107 GENERIC_DOCKER_ERROR = """\
108 Briefcase was unable to use Docker commands. Check your Docker
109 installation, and try again.
110 """
111 BUILDX_PLUGIN_MISSING = """\
112 Docker is installed and available for use but the buildx plugin
113 is not installed. Briefcase leverages the BuildKit Docker backend
114 to build Docker images and the buildx plugin makes this available.
115
116 See https://docs.docker.com/go/buildx/ to install the buildx plugin.
117 """
118
119 # Platform-specific template context dictionary for Docker installation details
120 DOCKER_INSTALL_URL: Mapping[str, str] = {
121 "Windows": "https://docs.docker.com/docker-for-windows/install/",
122 "Darwin": "https://docs.docker.com/docker-for-mac/install/",
123 "Linux": "https://docs.docker.com/engine/install/#server",
124 }
125
126 def __init__(self, tools: ToolCache, image_tag: str | None = None):
127 """A wrapper for the user-installed Docker.
128
129 :param tools: ToolCache of available tools
130 :param image_tag: An optional image used to access attributes of the Docker
131 environment, such as how user permissions are managed in bind mounts. A
132 lightweight image will be used if one is not specified but this image is not
133 at all bound to the instance.
134 """
135 super().__init__(tools=tools)
136 self.is_user_mapped = self._is_user_mapping_enabled(image_tag)
137
138 @classmethod
139 def verify_install(
140 cls,
141 tools: ToolCache,
142 image_tag: str | None = None,
143 **kwargs,
144 ) -> Docker:
145 """Verify Docker is installed and operational.
146
147 :param tools: ToolCache of available tools
148 :param image_tag: An optional image used during verification to access
149 attributes of the local Docker environment. This image is not bound to the
150 instance and only used during instantiation.
151 """
152 # short circuit since already verified and available
153 if hasattr(tools, "docker"):
154 return tools.docker
155
156 cls._version_compat(tools=tools)
157 cls._user_access(tools=tools)
158 cls._buildx_installed(tools=tools)
159
160 tools.docker = Docker(tools=tools, image_tag=image_tag)
161 return tools.docker
162
163 @classmethod
164 def _version_compat(cls, tools: ToolCache):
165 """Verify Docker version is compatible."""
166 try:
167 # Try to get the version of docker that is installed.
168 # expected output format: Docker version 25.0.2, build 29cf629\n
169 docker_version = (
170 tools.subprocess.check_output(
171 ["docker", "--version"],
172 env=cls.subprocess_env(),
173 )
174 .split("Docker version ")[1]
175 .split(",")[0]
176 .split("-")[0]
177 )
178
179 # Ensure Docker version is compatible
180 if Version(docker_version) < Version(cls.DOCKER_VERSION_MIN):
181 raise BriefcaseCommandError(
182 cls.WRONG_DOCKER_VERSION_ERROR.format(
183 version_min=cls.DOCKER_VERSION_MIN,
184 docker_version=docker_version,
185 install_url=cls.DOCKER_INSTALL_URL[tools.host_os],
186 )
187 )
188 except (InvalidVersion, IndexError):
189 tools.console.warning(cls.UNKNOWN_DOCKER_VERSION_WARNING)
190 except subprocess.CalledProcessError:
191 tools.console.warning(cls.DOCKER_INSTALLATION_STATUS_UNKNOWN_WARNING)
192 except OSError as e:
193 # Docker executable doesn't exist
194 raise BriefcaseCommandError(
195 cls.DOCKER_NOT_INSTALLED_ERROR.format(
196 install_url=cls.DOCKER_INSTALL_URL[tools.host_os]
197 )
198 ) from e
199
200 @classmethod
201 def _user_access(cls, tools: ToolCache):
202 """Verify Docker is operational for user."""
203 try:
204 # Invoke a docker command to check if the daemon is running,
205 # and the user has sufficient permissions.
206 # We don't care about the output, just that it succeeds.
207 tools.subprocess.check_output(
208 ["docker", "info"],
209 env=cls.subprocess_env(),
210 quiet=1,
211 )
212 except subprocess.CalledProcessError as e:
213 failure_output = e.output
214 if "permission denied while trying to connect" in failure_output:
215 raise BriefcaseCommandError(cls.LACKS_PERMISSION_ERROR) from e
216 elif (
217 # error message on Ubuntu
218 "Is the docker daemon running?" in failure_output
219 # error message on macOS
220 or "connect: connection refused" in failure_output
221 ):
222 raise BriefcaseCommandError(cls.DAEMON_NOT_RUNNING_ERROR) from e
223 else:
224 tools.subprocess.output_error(e)
225 raise BriefcaseCommandError(cls.GENERIC_DOCKER_ERROR) from e
226
227 @classmethod
228 def _buildx_installed(cls, tools: ToolCache):
229 """Verify the buildx plugin is installed."""
230 try:
231 tools.subprocess.check_output(
232 ["docker", "buildx", "version"],
233 env=cls.subprocess_env(),
234 )
235 except subprocess.CalledProcessError as e:
236 raise BriefcaseCommandError(cls.BUILDX_PLUGIN_MISSING) from e
237
238 def _write_test_path(self) -> Path:
239 """Host system filepath to perform write test from a container."""
240 return Path.cwd() / "build/container_write_test"
241
242 def _is_user_mapping_enabled(self, image_tag: str | None = None) -> bool:
243 """Determine whether Docker is mapping users between the container and the host.
244
245 Docker can be installed in different ways on Linux that significantly impact how
246 containers interact with the host system. Of particular note is ownership of
247 files and directories in bind mounts (i.e. mounts using --volume).
248
249 Traditionally, Docker would pass through the UID/GID of the user used inside a
250 container as the owner of files created within the bind mount. And since the
251 default user inside containers is root, the files would be owned by root on the
252 host file system; this prevents later interaction with those files by the host.
253 To work around this, the Dockerfile can use a step-down user with a UID and GID
254 that matches the host user running Docker.
255
256 Other installation methods of Docker, though, are not compatible with using such
257 a step-down user. This includes Docker Desktop and rootless Docker (although,
258 even a traditional installation of Docker Engine can be configured similarly).
259 In these modes, Docker maps the host user to the root user inside the container;
260 this mapping is transparent and would require changes to the host environment to
261 disable, if it can be disabled at all. This allows files created in bind mounts
262 inside the container to be owned on the host file system by the user running
263 Docker. Additionally, though, because the host user is mapped to root inside the
264 container, any files that were created by the host user in the bind mount
265 outside the container are owned by root inside the container; therefore, a step-
266 down user could not interact with such bind mount files inside the container.
267
268 To accommodate these different modes, this checks which user owns a file that is
269 created inside a bind mount in the container. If the owning user of that file on
270 the host file system is root, then a step-down user is necessary inside
271 containers. If the owning user is the host user, root should be used.
272
273 On macOS, Docker Desktop is the only option to use Docker and user mapping
274 happens differently such that any user in the container is mapped to the host
275 user. Instead of leveraging user namespaces as on Linux, this user mapping
276 manifests as a consequence of bind mounts being implemented as NFS shares
277 between macOS and the Linux VM that Docker Desktop runs containers in. So,
278 using a step-down user on macOS is effectively inconsequential.
279
280 On Windows WSL 2, Docker Desktop operates similarly to how it does on Linux.
281 However, user namespace mapping is not possible because the Docker Desktop VM
282 and the WSL distro are already running in different user namespaces...and
283 therefore, Docker cannot even see the users in the distro to map them in to the
284 container. So, a step-down user is always used.
285
286 ref: https://docs.docker.com/engine/security/userns-remap/
287
288 :param image_tag: The image:tag to use to create the container for the test; if
289 one is not specified, then `alpine:latest` will be used.
290 :returns: True if users are being mapped; False otherwise
291 """
292 host_write_test_path = self._write_test_path()
293 container_write_test_path = PurePosixPath(
294 f"/host_write_test/{host_write_test_path.name}"
295 )
296
297 host_write_test_path.parent.mkdir(exist_ok=True)
298
299 try:
300 host_write_test_path.unlink(missing_ok=True)
301 except OSError as e:
302 raise BriefcaseCommandError(
303 f"""\
304 The file path used to determine how Docker is mapping users between the host
305 and Docker containers already exists and cannot be automatically deleted.
306
307 {host_write_test_path}
308
309 Delete this file and run Briefcase again.
310 """
311 ) from e
312
313 image_tag = "alpine" if image_tag is None else image_tag
314 write_test_mounts = [
315 (host_write_test_path.parent, container_write_test_path.parent)
316 ]
317
318 # Write the test file in the bind mount inside the container
319 try:
320 self.check_output(
321 ["touch", container_write_test_path],
322 image_tag=image_tag,
323 mounts=write_test_mounts,
324 )
325 except subprocess.CalledProcessError as e:
326 raise BriefcaseCommandError(
327 "Unable to determine if Docker is mapping users"
328 ) from e
329
330 # If the file is not owned by `root`, then Docker is mapping usernames
331 is_user_mapped = self.tools.os.stat(host_write_test_path).st_uid != 0
332
333 # Delete the file inside the container since it may be owned by root on the host
334 try:
335 self.check_output(
336 ["rm", "-f", container_write_test_path],
337 image_tag=image_tag,
338 mounts=write_test_mounts,
339 )
340 except subprocess.CalledProcessError as e:
341 raise BriefcaseCommandError(
342 "Unable to clean up from determining if Docker is mapping users"
343 ) from e
344
345 return is_user_mapped
346
347 # B019 is a warning about @cache on methods possibly causing memory leaks,
348 # since the cache retains a reference to the instance that called the
349 # method. Since the Docker tools usually exist one at a time, this is not
350 # a big concern
351 @cache # noqa: B019
352 def cache_image(self, image_tag: str):
353 """Ensures an image is available and cached locally.
354
355 While many Docker commands for an image will pull that image in-line with the
356 command if it isn't already cached, this pollutes the console output with
357 details about pulling the image. This can be particularly troublesome when the
358 output from a command run inside a container using the image is desired.
359
360 Note: This will not update an already cached image if a newer version is
361 available in the registry.
362
363 :param image_tag: Image name/tag to pull if not locally cached
364 """
365 image_id = self.tools.subprocess.check_output(
366 ["docker", "images", "-q", image_tag],
367 env=self.subprocess_env(),
368 ).strip()
369
370 if not image_id:
371 self.tools.console.info(
372 f"Downloading Docker base image for {image_tag}...",
373 prefix=self.full_name,
374 )
375 try:
376 # disable streaming so image download progress bar is shown
377 self.tools.subprocess.run(
378 ["docker", "pull", image_tag],
379 check=True,
380 stream_output=False,
381 env=self.subprocess_env(),
382 )
383 except subprocess.CalledProcessError as e:
384 raise BriefcaseCommandError(
385 f"Unable to obtain the Docker image for {image_tag}. "
386 "Is the image name correct?"
387 ) from e
388
389 def check_output(self, args: SubprocessArgsT, image_tag: str, **kwargs) -> str:
390 """Run a process inside a Docker container, capturing output.
391
392 This ensures the image is locally cached and then runs a bare Docker invocation;
393 it's really only useful for running simple commands on an image, ensuring that
394 the container is destroyed afterward. In most cases, you'll want to use an app
395 context, rather than this.
396
397 :param args: The list of arguments to pass to the Docker instance.
398 :param image_tag: The Docker image to run
399 """
400 self.cache_image(image_tag)
401
402 # Any exceptions from running the process are *not* caught.
403 # This ensures that "docker.check_output()" behaves as closely to
404 # "subprocess.check_output()" as possible.
405 return self.tools.subprocess.check_output(
406 **self.dockerize_args(args, image_tag=image_tag, **kwargs)
407 )
408
409 @classmethod
410 def subprocess_env(cls, env: dict[str, str] | None = None) -> dict[str, str]:
411 """Adds environment variables to the context that Docker runs in."""
412 final_env = {
413 # Disable the hints/recommendations that Docker prints in the console
414 "DOCKER_CLI_HINTS": "false",
415 }
416 if env is not None:
417 final_env.update(env)
418 return final_env
419
420 def dockerize_args(
421 self,
422 args: SubprocessArgsT,
423 image_tag: str,
424 interactive: bool = False,
425 mounts: Iterable[tuple[str | os.PathLike, str | os.PathLike]] | None = None,
426 path_map: Mapping[str | os.PathLike, str | os.PathLike] | None = None,
427 env: Mapping[str, str | os.PathLike] | None = None,
428 cwd: str | os.PathLike | None = None,
429 add_hosts: Iterable[tuple[str, str]] | None = None,
430 **subprocess_kwargs,
431 ) -> dict[str, ...]: # pragma: no-cover-if-is-windows
432 """Convert arguments and environment into a Docker-compatible form.
433
434 Converts an argument and environment specification into a form that can be used
435 as arguments to invoke Docker. This involves:
436
437 * Ensuring the run deletes the container when it exits
438 * Adding volume bind mounts for specified paths
439 * Injecting environment variables in to the container's session
440 * Setting the current working directory for the container's session
441 * Adding additional DNS entries via /etc/hosts
442
443 :param args: The arguments for the command to be invoked
444 :param image_tag: The name of the image to start the container with
445 :param interactive: Start the container with stdin attached and a tty allocated
446 :param mounts: Bind mounts to add to the container
447 :param path_map: Mapping of files paths from the host to the container; these
448 mappings are applied to all values to be dockerized
449 :param env: The environment specification for the command to be executed
450 :param cwd: The working directory for the command to be executed
451 :param add_hosts: DNS mappings to add to the container's network
452 :param subprocess_kwargs: Keyword arguments passed through in return value
453 :returns: A dictionary of keyword arguments to drive subprocess calls
454 """
455 docker_cmdline = ["docker", "run", "--rm"]
456
457 # Add "-it" if in interactive mode
458 if interactive:
459 docker_cmdline.append("-it")
460
461 # Add volume mounts
462 # The :z suffix on volume mounts allows SELinux to modify the host mount;
463 # it is ignored on non-SELinux platforms
464 if mounts:
465 for source, target in mounts:
466 docker_cmdline.extend(
467 ("--volume", f"{os.fsdecode(source)}:{os.fsdecode(target)}:z")
468 )
469
470 # Pass environment variables in as --env arguments to Docker
471 if env:
472 for key, value in env.items():
473 docker_cmdline.extend(
474 ("--env", f"{key}={self.dockerize_path(value, path_map)}")
475 )
476
477 # Set a cwd as the working directory for the container
478 if cwd:
479 docker_cmdline.extend(("--workdir", self.dockerize_path(cwd, path_map)))
480
481 # Host mappings to add to container's /etc/hosts
482 if add_hosts:
483 for host_name, address in add_hosts:
484 docker_cmdline.extend(("--add-host", f"{host_name}:{address}"))
485
486 # Add the image name to create the temporary container with
487 docker_cmdline.append(image_tag)
488
489 # Finally, add the command (and its arguments) to run in the container
490 docker_cmdline.extend(self.dockerize_path(arg, path_map) for arg in args)
491
492 # Augment configuration to drive the subprocess call
493 subprocess_kwargs["args"] = docker_cmdline
494 subprocess_kwargs["env"] = self.subprocess_env()
495
496 return subprocess_kwargs
497
498 def dockerize_path(
499 self,
500 arg: str | os.PathLike,
501 path_map: Mapping[str | os.PathLike, str | os.PathLike] | None = None,
502 ) -> str: # pragma: no-cover-if-is-windows
503 """Translates host file paths into the equivalent location in the docker
504 filesystem as defined by a file path mapping.
505
506 Additionally, fsdecode() is called for the input value to ensure it's something
507 that can represent a path and will always be returned as a string.
508
509 :param arg: The argument to convert to dockerized paths
510 :param path_map: A mapping of host file system paths to the docker container
511 file system; e.g. $HOME/.cache/briefcase -> /briefcase, such that,
512 $HOME/.cache/briefcase/tools/java becomes /briefcase/tools/java
513 :returns: A string where all convertible paths have been replaced
514 """
515 arg = os.fsdecode(arg)
516
517 if path_map:
518 for source, target in path_map.items():
519 arg = arg.replace(os.fsdecode(source), os.fsdecode(target))
520
521 return arg
522
523 @contextlib.contextmanager
524 def x11_passthrough(
525 self, subprocess_kwargs: dict[str, ...]
526 ) -> dict[str, ...]: # pragma: no-cover-if-is-windows
527 """Manager to expose the host's X11 server to a container.
528
529 This allows Docker containers to use the host's X11 server with the
530 authorization afforded to the current user. The user's X11 auth is copied and
531 modified in a dedicated temporary xauth file. A TCP server is set up to spoof a
532 new X display and proxies X commands to the current display. The XAUTHORITY
533 environment variable is set to the temporary xauth file and DISPLAY is set to
534 "host.docker.internal:<display number>" so that the container sends X commands
535 through a Docker-provided mapping of the host's network interface to the spoofed
536 display that finally proxies those commands to the actual display.
537
538 Full docs: https://briefcase.readthedocs.io/en/latest/how-to/internal/x11passthrough.html
539
540 :param subprocess_kwargs: Existing keywords args from the caller
541 :returns: augmented keyword args for the call to subprocess
542 """
543 if not (DISPLAY := self.tools.os.getenv("DISPLAY")):
544 raise BriefcaseCommandError(
545 "The DISPLAY environment variable must be set to run an app in Docker"
546 )
547
548 # Create a TCP proxy for a spoofed X display
549 proxy_popen, proxy_display_num = self._x11_tcp_proxy(DISPLAY)
550
551 # Define the xauth database files for the spoofed display
552 xauth_file_path = self._x11_proxy_display_xauth_file_path(proxy_display_num)
553 docker_xauth_file_path = PurePosixPath("/tmp") / xauth_file_path.name
554 try:
555 # Create the xauth database file for the spoofed display
556 try:
557 self._x11_write_xauth_file(DISPLAY, xauth_file_path, proxy_display_num)
558 except XauthDatabaseCreationFailure:
559 self.tools.console.warning(
560 """\
561 An X11 authentication database could not be created for the display.
562
563 Briefcase will proceed, but if access to the display is rejected, this may be why.
564 """
565 )
566 else:
567 # Add the xauth database to the container
568 subprocess_kwargs.setdefault("mounts", []).append(
569 (xauth_file_path, docker_xauth_file_path)
570 )
571 # Tell X clients to use the xauth database to connect to the display
572 subprocess_kwargs.setdefault("env", {}).update(
573 {"XAUTHORITY": docker_xauth_file_path}
574 )
575
576 # This updates the container's /etc/hosts with a mapping for
577 # `host.docker.internal` to a network address for the host such that
578 # network-based services on the host can be reached within the container.
579 #
580 # The keyword `host.docker.internal` is already always defined for
581 # containers created by Docker Desktop via the DNS configured within its
582 # Linux VM. However, for Docker Engine, DNS is managed by the Linux host;
583 # therefore, this mapping for `host.docker.internal` must be defined each
584 # time a container is started.
585 #
586 # The keyword `host-gateway` is interpreted and replaced with a network
587 # address for the host by the Docker server when a container starts. The
588 # specific network address used here will be dependent on the Docker
589 # implementation, but it will likely be either the address for `docker0` or
590 # and address for the host otherwise mapped through to the container.
591 subprocess_kwargs.setdefault("add_hosts", []).append(
592 ("host.docker.internal", "host-gateway")
593 )
594
595 # Finally, tell X clients to use the spoofed display
596 subprocess_kwargs.setdefault("env", {}).update(
597 {"DISPLAY": f"host.docker.internal:{proxy_display_num}"}
598 )
599
600 yield subprocess_kwargs
601
602 finally:
603 self.tools.subprocess.cleanup("X display proxy", proxy_popen)
604 xauth_file_path.unlink(missing_ok=True)
605
606 def _x11_tcp_proxy(self, DISPLAY: str) -> tuple[subprocess.Popen, int]:
607 """Starts a TCP proxy as a spoofed X display.
608
609 The TCP server's port is chosen as 6000 + the display number as defined in the
610 X11 standard. In this way, when X clients attempt to make a connection for the
611 chosen display number, this TCP port will be automatically evaluated by the
612 client for consideration as an X display.
613
614 The proxy is bound to 0.0.0.0 and as such will be reachable on all network
615 interfaces defined for the host. Ideally, the proxy would only need to bind to
616 the network bridge defined by Docker, usually `docker0`, but Docker Desktop is
617 not able to use a shared network interface bridge as Docker Engine does since
618 it runs containers inside a Linux VM. Instead, it attaches the host's primary
619 network interface as a device on a virtual network interface bridge created by
620 the VM. Because of this, the proxy must be exposed to the network at large to
621 also be exposed within the container.
622
623 :param DISPLAY: value of DISPLAY environment variable
624 :returns: the Popen process for the proxy and the display number it is using
625 """
626 if not self.tools.shutil.which("socat"):
627 raise BriefcaseCommandError(
628 "Install socat to run an app for a targeted Linux distribution"
629 )
630
631 try:
632 # The DISPLAY environment variable is expected to be of the form:
633 # [hostname]:[display number].[screen number]
634 display_num = int(DISPLAY.split(":")[1].split(".")[0])
635 except (IndexError, ValueError, AttributeError) as e:
636 raise BriefcaseCommandError(
637 f"Unsupported value for environment variable DISPLAY: {str(DISPLAY)!r}"
638 ) from e
639
640 proxy_display_num = self._x11_allocate_display()
641 proxy_display_tcp_port = 6000 + proxy_display_num
642
643 # If a TCP server is already running for the X display on the host, then start
644 # a proxy to that TCP server for the display. While most distros do not support
645 # TCP for an X display by default, X11 forwarding over SSH is facilitated by
646 # opening an SSH channel on the port for the X display; so, proxying to that
647 # channel allows the container to use the X display exposed by X11 forwarding.
648 if self._x11_is_display_tcp(display_num):
649 proxy_process = self.tools.subprocess.Popen(
650 [
651 "socat",
652 f"TCP-LISTEN:{proxy_display_tcp_port},reuseaddr,fork,bind=0.0.0.0",
653 f"TCP:localhost:{6000 + display_num}",
654 ]
655 )
656
657 # Otherwise, just proxy to the UNIX socket for the display
658 elif self._x11_is_display_unix(display_num):
659 proxy_process = self.tools.subprocess.Popen(
660 [
661 "socat",
662 f"TCP-LISTEN:{proxy_display_tcp_port},reuseaddr,fork,bind=0.0.0.0",
663 f"UNIX-CONNECT:/tmp/.X11-unix/X{display_num}",
664 ]
665 )
666
667 else:
668 raise BriefcaseCommandError(f"Cannot find X11 display for {DISPLAY!r}")
669
670 return proxy_process, proxy_display_num
671
672 def _x11_proxy_display_xauth_file_path(
673 self, display_num: int
674 ) -> PosixPath: # pragma: no-cover-if-is-windows
675 """Path to the xauth database for the proxy display.
676
677 The project's build directory is used to accommodate Docker Desktop. By default,
678 Docker Desktop only allows bind mounts from directories/files within the user's
679 home directory. So, while it may be more appropriate to use a dedicated temp
680 directory, such as /tmp, this avoids having to instruct users to add that
681 directory as a source of possible bind mounts.
682 """
683 return PosixPath.cwd() / f"build/.briefcase.docker.xauth.{display_num}"
684
685 def _x11_allocate_display(self) -> int:
686 """Finds available X display number for use; raises otherwise.
687
688 A universal mechanism to request and reserve an X display does not exist. On
689 most systems, though, there will not be many active X displays. So, this
690 approach is similar to that of OpenSSH's strategy for reserving an X display
691 for X11 forwarding: simply iterate over candidate display numbers using the
692 first one that is not already is use.
693
694 This check for whether a display number is already in use is limited to
695 verifying a TCP server or UNIX socket does not already exist for the display.
696 While other transport protocols are possible, any modern system should be using
697 at least one of these transports in tandem with anything else.
698 """
699 # This range of candidate display numbers is arbitrary. Typically, locally
700 # configured displays start at number 0 while SSH displays start at number 10.
701 # So, in the common case, this is expected to return the first candidate.
702 # Although, in cases where parts of this range are already allocated, the check
703 # for a UNIX socket is immediate while the TCP check must actually attempt to
704 # connect to the port; in practice, this should also be immediate as anything
705 # listening accepts the connection or the OS rejects it since nothing is there.
706 for num in range(50, 299 + 1):
707 if not (self._x11_is_display_unix(num) or self._x11_is_display_tcp(num)):
708 display_num = num
709 break
710 else:
711 raise BriefcaseCommandError("Failed to allocate X11 display")
712
713 return display_num
714
715 def _x11_is_display_tcp(self, display_num: int) -> bool:
716 """Is a TCP server running for the X display?"""
717 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
718 sock.settimeout(3)
719 try:
720 # returns 0 only if the connection is successful
721 return sock.connect_ex(("localhost", 6000 + display_num)) == 0
722 except OSError:
723 return False
724
725 def _x11_display_unix_socket_path(
726 self, display_num: int
727 ) -> PosixPath: # pragma: no-cover-if-is-windows
728 """Path to the UNIX socket for the display."""
729 return PosixPath(f"/tmp/.X11-unix/X{display_num}")
730
731 def _x11_is_display_unix(
732 self, display_num: int
733 ) -> bool: # pragma: no-cover-if-is-windows
734 """Is a UNIX socket running for the X display?"""
735 try:
736 return self._x11_display_unix_socket_path(display_num).is_socket()
737 except OSError:
738 return False
739
740 def _x11_write_xauth_file(
741 self,
742 DISPLAY: str,
743 xauth_file_path: Path,
744 target_display_num: int,
745 ) -> None:
746 """Writes a xauth file using the current user's X authorization.
747
748 :param DISPLAY: Value of DISPLAY environment variable
749 :param xauth_file_path: File path to write xauth database for target display
750 :param target_display_num: Number of targeted X display
751 """
752 if not self.tools.shutil.which("xauth"):
753 raise BriefcaseCommandError(
754 "Install xauth to run an app for a targeted Linux distribution"
755 )
756
757 # Extract the 32 byte X auth cookie for the current display
758 # `xauth nlist` outputs the auth C struct defined by the libxau library
759 try:
760 x_display_auth_cookie = (
761 self.tools.subprocess.check_output(["xauth", "-i", "nlist", DISPLAY])
762 .splitlines()[0]
763 .split(" ")[8] # assumed to be a MIT-MAGIC-COOKIE-1
764 )
765 except (subprocess.CalledProcessError, IndexError) as e:
766 raise XauthDatabaseCreationFailure("Failed to retrieve xauth cookie") from e
767
768 # Initialize X authentication file
769 xauth_file_path.parent.mkdir(parents=True, exist_ok=True)
770 xauth_file_path.unlink(missing_ok=True)
771 xauth_file_path.touch()
772
773 # Create an xauth database for the target display
774 # using the current display's cookie
775 try:
776 self.tools.subprocess.check_output(
777 [
778 "xauth",
779 "-i",
780 "-f",
781 xauth_file_path,
782 "add",
783 f":{target_display_num}",
784 "MIT-MAGIC-COOKIE-1",
785 x_display_auth_cookie,
786 ]
787 )
788 except subprocess.CalledProcessError as e:
789 raise XauthDatabaseCreationFailure(
790 "Failed to add a xauth entry for existing cookie"
791 ) from e
792
793 # Retrieve xauth list that was just written for the target display
794 try:
795 xauth_list = self.tools.subprocess.check_output(
796 ["xauth", "-i", "-f", xauth_file_path, "nlist"]
797 )
798 except subprocess.CalledProcessError as e:
799 raise XauthDatabaseCreationFailure("Failed to retrieve xauth list") from e
800
801 # When an X auth entry is added to a xauth database, the auth is tied to a
802 # hostname and a display number. Since this X auth will be used to connect to
803 # the host machine's X server via a proxy exposed within the container, those
804 # connections will be using a different hostname for the display. Therefore,
805 # this replaces the hostname in the auth entry with the "FamilyWild" tag which
806 # allows using the auth for the display regardless of the targeted hostname.
807 xauth_list = "\n".join("ffff" + line[4:] for line in xauth_list.splitlines())
808
809 # Re-write xauth for target display to support any target hostname
810 try:
811 self.tools.subprocess.check_output(
812 ["xauth", "-i", "-f", xauth_file_path, "nmerge", "-"],
813 input=xauth_list,
814 )
815 except subprocess.CalledProcessError as e:
816 raise XauthDatabaseCreationFailure(
817 "Failed to merge xauth updates for FamilyWild hostname"
818 ) from e
819
820
821 class DockerAppContext(Tool):
822 name = "docker_app_context"
823 full_name = "Docker"
824
825 def __init__(self, tools: ToolCache, app: AppConfig):
826 super().__init__(tools=tools)
827 self.app: AppConfig = app
828 self.app_base_path: Path
829 self.host_bundle_path: Path
830 self.host_data_path: Path
831 self.image_tag: str
832 self.python_version: str
833
834 @property
835 def docker_briefcase_path(self) -> PurePosixPath:
836 """The briefcase data directory used inside container."""
837 return PurePosixPath("/briefcase")
838
839 @classmethod
840 def verify_install(
841 cls,
842 tools: ToolCache,
843 app: AppConfig,
844 image_tag: str,
845 dockerfile_path: Path,
846 app_base_path: Path,
847 host_bundle_path: Path,
848 host_data_path: Path,
849 python_version: str,
850 extra_build_args: list[str] | None = None,
851 **kwargs,
852 ) -> DockerAppContext: # pragma: no-cover-if-is-windows
853 """Verify that docker is available as an app-bound tool.
854
855 Creates or updates the Docker image for the app to run commands in a context for
856 the App.
857
858 :param tools: ToolCache of available tools
859 :param app: Current Appconfig
860 :param image_tag: Tag to assign to Docker image
861 :param dockerfile_path: Dockerfile to use to build Docker image
862 :param app_base_path: Base directory path for App
863 :param host_bundle_path: Base directory for where App is built
864 :param host_data_path: Base directory for host's Briefcase data
865 :param python_version: Version of python, e.g. 3.10
866 :returns: A wrapper for a Docker app context.
867 """
868 # short circuit since already verified and available
869 if hasattr(tools[app], "app_context"):
870 return tools[app].app_context
871
872 Docker.verify(tools=tools)
873
874 tools[app].app_context = DockerAppContext(tools=tools, app=app)
875 tools[app].app_context.prepare(
876 image_tag=image_tag,
877 dockerfile_path=dockerfile_path,
878 app_base_path=app_base_path,
879 host_bundle_path=host_bundle_path,
880 host_data_path=host_data_path,
881 python_version=python_version,
882 extra_build_args=extra_build_args,
883 )
884 return tools[app].app_context
885
886 def prepare(
887 self,
888 image_tag: str,
889 dockerfile_path: Path,
890 app_base_path: Path,
891 host_bundle_path: Path,
892 host_data_path: Path,
893 python_version: str,
894 extra_build_args: list[str] | None = None,
895 ):
896 """Create/update the Docker image from the app's Dockerfile."""
897 self.app_base_path = app_base_path
898 self.host_bundle_path = host_bundle_path
899 self.host_data_path = host_data_path
900 self.image_tag = image_tag
901 self.python_version = python_version
902
903 self.tools.console.info(
904 "Building Docker container image...",
905 prefix=self.app.app_name,
906 )
907 with self.tools.console.wait_bar("Building Docker image..."):
908 # Install requirements for both building *and* running the app
909 # (ensure a copy of system_requires is used to avoid modification)
910 system_requires = getattr(self.app, "system_requires", []).copy()
911 system_requires.extend(getattr(self.app, "system_runtime_requires", []))
912
913 with self.tools.console.context("Docker"):
914 try:
915 self.tools.subprocess.run(
916 [
917 "docker",
918 "buildx",
919 "build",
920 "--load",
921 "--progress",
922 "plain",
923 "--tag",
924 self.image_tag,
925 "--file",
926 dockerfile_path,
927 "--build-arg",
928 f"SYSTEM_REQUIRES={' '.join(system_requires)}",
929 "--build-arg",
930 f"HOST_UID={self.tools.os.getuid()}",
931 "--build-arg",
932 f"HOST_GID={self.tools.os.getgid()}",
933 Path(
934 self.app_base_path,
935 *self.app.sources[0].split("/")[:-1],
936 ),
937 ]
938 + (extra_build_args if extra_build_args is not None else []),
939 check=True,
940 )
941 except subprocess.CalledProcessError as e:
942 raise BriefcaseCommandError(
943 f"Error building Docker container image "
944 f"for {self.app.app_name}."
945 ) from e
946
947 @contextlib.contextmanager
948 def run_app_context(self, subprocess_kwargs: dict[str, ...]) -> dict[str, ...]:
949 """Manager to run a Briefcase project app in a container.
950
951 :returns: context manager to wrap the call to Popen/run/check_output()
952 """
953 with self.tools.docker.x11_passthrough(subprocess_kwargs) as subprocess_kwargs:
954 yield subprocess_kwargs
955
956 def run(self, args: SubprocessArgsT, **kwargs) -> None:
957 """Run a process inside a Docker container."""
958 # Any exceptions from running the process are *not* caught.
959 # This ensures that "docker.run()" behaves as closely to
960 # "subprocess.run()" as possible.
961 if kwargs.get("interactive"):
962 kwargs["stream_output"] = False
963
964 with self.tools.console.context("Docker"):
965 self.tools.subprocess.run(**self._dockerize_args(args, **kwargs))
966
967 def check_output(self, args: SubprocessArgsT, **kwargs) -> str:
968 """Capture and return output from a process inside a Docker container."""
969 # Any exceptions from running the process are *not* caught.
970 # This ensures that "docker.check_output()" behaves as closely to
971 # "subprocess.check_output()" as possible.
972 return self.tools.subprocess.check_output(
973 **self._dockerize_args(args, **kwargs)
974 )
975
976 def Popen(self, args: SubprocessArgsT, **kwargs) -> subprocess.Popen:
977 """Open and return a process running inside a Docker container."""
978 return self.tools.subprocess.Popen(**self._dockerize_args(args, **kwargs))
979
980 def _dockerize_args(
981 self, args: SubprocessArgsT, **kwargs
982 ) -> dict[str, ...]: # pragma: no-cover-if-is-windows
983 """App-specific wrapper for Docker.dockerize_args().
984
985 Uses the app's dedicated Docker image to run the container.
986
987 Adds app's bundle directory and the Briefcase data directory as bind mounts.
988
989 All bind mount definitions also serve as path mappings from the host in to the
990 container file system; these mappings are applied to the command arguments,
991 environment variable values, and the working directory.
992 """
993 kwargs["image_tag"] = self.image_tag
994
995 kwargs.setdefault("mounts", []).extend(
996 [
997 (self.host_bundle_path, "/app"),
998 (self.host_data_path, self.docker_briefcase_path),
999 ]
1000 )
1001
1002 kwargs.setdefault("path_map", {}).update(dict(kwargs["mounts"]))
1003
1004 # Convert fully-qualified paths for the host's Python to the unqualified Python
1005 # binary available inside the container
1006 kwargs["path_map"][sys.executable] = f"python{self.python_version}"
1007
1008 return self.tools.docker.dockerize_args(args, **kwargs)