|
| 1 | +import contextlib |
| 2 | +import io |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import shutil |
| 6 | +import sys |
| 7 | +import tempfile |
| 8 | + |
| 9 | +import docker |
| 10 | +from docker.models.containers import Container |
| 11 | + |
| 12 | + |
| 13 | +class ContainerUtils(object): |
| 14 | + """ |
| 15 | + Provides functionality related to Docker containers |
| 16 | + """ |
| 17 | + |
| 18 | + @staticmethod |
| 19 | + @contextlib.contextmanager |
| 20 | + def automatically_stop(container: Container, timeout: int = 1): |
| 21 | + """ |
| 22 | + Context manager to automatically stop a container returned by `ContainerUtils.start_for_exec()` |
| 23 | + """ |
| 24 | + try: |
| 25 | + yield container |
| 26 | + finally: |
| 27 | + logging.info("Stopping Docker container {}...".format(container.short_id)) |
| 28 | + container.stop(timeout=timeout) |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def copy_from_host( |
| 32 | + container: Container, host_path: str, container_path: str |
| 33 | + ) -> None: |
| 34 | + """ |
| 35 | + Copies a file or directory from the host system to a container returned by `ContainerUtils.start_for_exec()`. |
| 36 | +
|
| 37 | + `host_path` is the absolute path to the file or directory on the host system. |
| 38 | +
|
| 39 | + `container_path` is the absolute path to the directory in the container where the copied file(s) will be placed. |
| 40 | + """ |
| 41 | + |
| 42 | + # If the host path denotes a file rather than a directory, copy it to a temporary directory |
| 43 | + # (If the host path is a directory then we create a no-op context manager to use in our `with` statement below) |
| 44 | + tempDir = contextlib.suppress() |
| 45 | + if os.path.isfile(host_path): |
| 46 | + tempDir = tempfile.TemporaryDirectory() |
| 47 | + shutil.copy2( |
| 48 | + host_path, os.path.join(tempDir.name, os.path.basename(host_path)) |
| 49 | + ) |
| 50 | + host_path = tempDir.name |
| 51 | + |
| 52 | + # Automatically delete the temporary directory if we created one |
| 53 | + with tempDir: |
| 54 | + # Create a temporary file to hold the .tar archive data |
| 55 | + with tempfile.NamedTemporaryFile( |
| 56 | + suffix=".tar", delete=False |
| 57 | + ) as tempArchive: |
| 58 | + # Add the data from the host system to the temporary archive |
| 59 | + tempArchive.close() |
| 60 | + archiveName = os.path.splitext(tempArchive.name)[0] |
| 61 | + shutil.make_archive(archiveName, "tar", host_path) |
| 62 | + |
| 63 | + # Copy the data from the temporary archive to the container |
| 64 | + with open(tempArchive.name, "rb") as archive: |
| 65 | + container.put_archive(container_path, archive.read()) |
| 66 | + |
| 67 | + # Remove the temporary archive |
| 68 | + os.unlink(tempArchive.name) |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def exec(container: Container, command: [str], capture: bool = False, **kwargs): |
| 72 | + """ |
| 73 | + Executes a command in a container returned by `ContainerUtils.start_for_exec()` and streams or captures the output |
| 74 | + """ |
| 75 | + |
| 76 | + # Determine if we are capturing the output or printing it |
| 77 | + stdoutDest = io.StringIO() if capture else sys.stdout |
| 78 | + stderrDest = io.StringIO() if capture else sys.stderr |
| 79 | + |
| 80 | + # Attempt to start the command |
| 81 | + details = container.client.api.exec_create(container.id, command, **kwargs) |
| 82 | + output = container.client.api.exec_start(details["Id"], stream=True, demux=True) |
| 83 | + |
| 84 | + # Stream the output |
| 85 | + for chunk in output: |
| 86 | + # Isolate the stdout and stderr chunks |
| 87 | + stdout, stderr = chunk |
| 88 | + |
| 89 | + # Capture/print the stderr data if we have any |
| 90 | + if stderr is not None: |
| 91 | + print(stderr.decode("utf-8"), end="", flush=True, file=stderrDest) |
| 92 | + |
| 93 | + # Capture/print the stdout data if we have any |
| 94 | + if stdout is not None: |
| 95 | + print(stdout.decode("utf-8"), end="", flush=True, file=stdoutDest) |
| 96 | + |
| 97 | + # Determine if the command succeeded |
| 98 | + capturedOutput = ( |
| 99 | + (stdoutDest.getvalue(), stderrDest.getvalue()) if capture else None |
| 100 | + ) |
| 101 | + result = container.client.api.exec_inspect(details["Id"])["ExitCode"] |
| 102 | + if result != 0: |
| 103 | + container.stop() |
| 104 | + raise RuntimeError( |
| 105 | + "Failed to run command {} in container. Process returned exit code {} with output {}.".format( |
| 106 | + command, |
| 107 | + result, |
| 108 | + capturedOutput if capture else "printed above", |
| 109 | + ) |
| 110 | + ) |
| 111 | + |
| 112 | + # If we captured the output then return it |
| 113 | + return capturedOutput |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def start_for_exec( |
| 117 | + client: docker.DockerClient, image: str, platform: str, **kwargs |
| 118 | + ) -> Container: |
| 119 | + """ |
| 120 | + Starts a container in a detached state using a command that will block indefinitely |
| 121 | + and returns the container handle. The handle can then be used to execute commands |
| 122 | + inside the container. The container will be removed automatically when it is stopped, |
| 123 | + but it will need to be stopped manually by calling `ContainerUtils.stop()`. |
| 124 | + """ |
| 125 | + command = ( |
| 126 | + ["timeout", "/t", "99999", "/nobreak"] |
| 127 | + if platform == "windows" |
| 128 | + else ["bash", "-c", "sleep infinity"] |
| 129 | + ) |
| 130 | + return client.containers.run( |
| 131 | + image, |
| 132 | + command, |
| 133 | + stdin_open=platform == "windows", |
| 134 | + tty=platform == "windows", |
| 135 | + detach=True, |
| 136 | + remove=True, |
| 137 | + **kwargs, |
| 138 | + ) |
0 commit comments