-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdocker_runner.py
58 lines (51 loc) · 1.91 KB
/
docker_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import logging
from types import TracebackType
from typing import Optional
import docker
from docker.models.containers import Container
LOGGER = logging.getLogger(__name__)
class DockerRunner:
def __init__(
self,
image_name: str,
docker_client: docker.DockerClient = docker.from_env(),
command: str = "sleep infinity",
):
self.container: Optional[Container] = None
self.image_name: str = image_name
self.command: str = command
self.docker_client: docker.DockerClient = docker_client
def __enter__(self) -> Container:
LOGGER.info(f"Creating container for image {self.image_name} ...")
self.container = self.docker_client.containers.run(
image=self.image_name,
command=self.command,
detach=True,
)
LOGGER.info(f"Container {self.container.name} created")
return self.container
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
assert self.container is not None
LOGGER.info(f"Removing container {self.container.name} ...")
if self.container:
self.container.remove(force=True)
LOGGER.info(f"Container {self.container.name} removed")
@staticmethod
def run_simple_command(
container: Container, cmd: str, print_result: bool = True
) -> str:
LOGGER.info(f"Running cmd: '{cmd}' on container: {container}")
out = container.exec_run(cmd)
result = out.output.decode("utf-8").rstrip()
assert isinstance(result, str)
if print_result:
LOGGER.info(f"Command result: {result}")
assert out.exit_code == 0, f"Command: {cmd} failed"
return result