|
a |
|
b/tests/lib/docker.py |
|
|
1 |
import os |
|
|
2 |
|
|
|
3 |
import docker |
|
|
4 |
from docker.errors import ContainerError, NotFound |
|
|
5 |
|
|
|
6 |
|
|
|
7 |
__all__ = ["ContainerError", "Containers"] |
|
|
8 |
|
|
|
9 |
|
|
|
10 |
class Containers: |
|
|
11 |
def __init__(self): |
|
|
12 |
self._docker = docker.from_env() |
|
|
13 |
|
|
|
14 |
def get_engine_version(self): # pragma: no cover |
|
|
15 |
versions = self._docker.version() |
|
|
16 |
engine_details = [c for c in versions["Components"] if c["Name"] == "Engine"] |
|
|
17 |
assert len(engine_details) == 1 |
|
|
18 |
return engine_details[0]["Version"] |
|
|
19 |
|
|
|
20 |
def get_container(self, name): |
|
|
21 |
return self._docker.containers.get(name) |
|
|
22 |
|
|
|
23 |
def is_running(self, name): |
|
|
24 |
try: |
|
|
25 |
container = self.get_container(name) |
|
|
26 |
return container.status == "running" # pragma: no cover |
|
|
27 |
except NotFound: # pragma: no cover |
|
|
28 |
return False |
|
|
29 |
|
|
|
30 |
def get_mapped_port_for_host(self, name, container_port): |
|
|
31 |
""" |
|
|
32 |
Given a port on a container return the port on the host to which it is |
|
|
33 |
mapped |
|
|
34 |
""" |
|
|
35 |
container_port = f"{container_port}/tcp" |
|
|
36 |
container = self.get_container(name) |
|
|
37 |
port_config = container.attrs["NetworkSettings"]["Ports"][container_port] |
|
|
38 |
host_port = port_config[0]["HostPort"] |
|
|
39 |
return host_port |
|
|
40 |
|
|
|
41 |
def get_container_ip(self, name): |
|
|
42 |
""" |
|
|
43 |
Given a container name, return it IP address |
|
|
44 |
""" |
|
|
45 |
container = self.get_container(name) |
|
|
46 |
return container.attrs["NetworkSettings"]["IPAddress"] |
|
|
47 |
|
|
|
48 |
# All available arguments documented here: |
|
|
49 |
# https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.ContainerCollection.run |
|
|
50 |
def run_bg(self, name, image, **kwargs): # pragma: no cover |
|
|
51 |
return self._run(name=name, image=image, detach=True, **kwargs) |
|
|
52 |
|
|
|
53 |
# All available arguments documented here: |
|
|
54 |
# https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.ContainerCollection.run |
|
|
55 |
def run_captured(self, image, **kwargs): |
|
|
56 |
return self._run(image=image, detach=False, stdout=True, stderr=True, **kwargs) |
|
|
57 |
|
|
|
58 |
def _run(self, **kwargs): # pragma: no cover |
|
|
59 |
# Run as non-root by default to match production |
|
|
60 |
kwargs.setdefault("user", os.getuid()) |
|
|
61 |
return self._docker.containers.run(remove=True, **kwargs) |