Runs a command in a docker container and streams logs. Args: command: The command to run. volumes: A dictionary of volumes to mount. image: The docker image to use. privileged: Whether to run the container as privileged. Returns: True on success, False otherwise.
(
command: list[str],
volumes: dict,
image: str,
privileged: bool = False,
)
| 109 | |
| 110 | |
| 111 | def run_command( |
| 112 | command: list[str], |
| 113 | volumes: dict, |
| 114 | image: str, |
| 115 | privileged: bool = False, |
| 116 | ) -> bool: |
| 117 | """Runs a command in a docker container and streams logs. |
| 118 | |
| 119 | Args: |
| 120 | command: The command to run. |
| 121 | volumes: A dictionary of volumes to mount. |
| 122 | image: The docker image to use. |
| 123 | privileged: Whether to run the container as privileged. |
| 124 | |
| 125 | Returns: |
| 126 | True on success, False otherwise. |
| 127 | """ |
| 128 | client = check_docker_setup() |
| 129 | if not client: |
| 130 | return False |
| 131 | |
| 132 | if not pull_image(image): |
| 133 | return False |
| 134 | |
| 135 | container_instance = None |
| 136 | try: |
| 137 | click.echo(f'Running command in Docker container: {command}') |
| 138 | container_instance = client.containers.run( |
| 139 | image, |
| 140 | command, |
| 141 | volumes=volumes, |
| 142 | working_dir=_DEFAULT_WORKING_DIR, |
| 143 | privileged=privileged, |
| 144 | detach=True, |
| 145 | remove=False) # Can't auto-remove if we want to stream logs |
| 146 | |
| 147 | for line in container_instance.logs(stream=True, follow=True): |
| 148 | click.echo(line.decode('utf-8').strip()) |
| 149 | |
| 150 | result = container_instance.wait() |
| 151 | if result['StatusCode'] != 0: |
| 152 | # Get final logs in case of error |
| 153 | error_logs = container_instance.logs().decode('utf-8') |
| 154 | click.secho( |
| 155 | 'Error: Command failed in Docker container with exit code ' |
| 156 | f'{result["StatusCode"]}.', |
| 157 | fg='red') |
| 158 | click.secho(error_logs, fg='red') |
| 159 | return False |
| 160 | |
| 161 | return True |
| 162 | except docker.errors.ContainerError as e: |
| 163 | click.secho(f'Error: Command failed in Docker container: {e}', fg='red') |
| 164 | if e.stderr: |
| 165 | click.secho(e.stderr.decode('utf-8'), fg='red') |
| 166 | return False |
| 167 | except docker.errors.ImageNotFound as e: |
| 168 | click.secho(f'Error: Docker image {image} not found: {e}', fg='red') |
nothing calls this directly
no test coverage detected