Debian Codegraph @

tests/test_docker.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 """
2 Test labgrid code of communicating with a docker daemon and using it
3 for creating, starting and accessing a docker container.
4 """
5
6 import pytest
7 import io
8
9 from labgrid import Environment
10 from labgrid.driver import DockerDriver
11 from labgrid.resource.docker import DockerConstants
12 from labgrid.exceptions import NoResourceFoundError
13
14 pytest.importorskip("docker")
15
16
17 def check_external_progs_present():
18 """Determine if host machine has a usable docker daemon"""
19 try:
20 import docker
21
22 try:
23 dock = docker.from_env()
24 dock.info()
25 except docker.errors.DockerException:
26 return False
27 except OSError:
28 return False
•29 except docker.errors.DockerException:
30 return False
31 return True
32
33
34 @pytest.fixture
35 def docker_env(tmp_path_factory):
36 """Create Environment instance from the given inline YAML file."""
37 p = tmp_path_factory.mktemp("docker") / "config.yaml"
38 # Note: The SSHDriver part at bottom is only used by the test that
39 # will run if a docker daemon is present, not by
40 # test_driver_without_daemon.
41 p.write_text(
42 """
43 targets:
44 main:
45 resources:
46 - DockerDaemon:
47 docker_daemon_url: "unix:///var/run/docker.sock"
48 drivers:
49 - DockerDriver:
50 image_uri: "rastasheep/ubuntu-sshd:16.04"
51 pull: 'missing'
52 container_name: "ubuntu-lg-example"
53 host_config: {"network_mode": "bridge"}
54 network_services: [
55 {"port": 22, "username": "root", "password": "root"}]
56 - DockerStrategy: {}
57 - SSHDriver:
58 keyfile: ""
59 """
60 )
61 return Environment(str(p))
62
63
64 @pytest.fixture
65 def docker_env_for_local_container(tmp_path_factory):
66 """Create Environment instance from the given inline YAML file."""
67 p = tmp_path_factory.mktemp("docker") / "config.yaml"
68 p.write_text(
69 """
70 targets:
71 main:
72 resources:
73 - DockerDaemon:
74 docker_daemon_url: "unix:///var/run/docker.sock"
75 drivers:
76 - DockerDriver:
77 image_uri: "local_rastasheep"
78 pull: "never"
79 container_name: "ubuntu-lg-example"
80 host_config: {"network_mode": "bridge"}
81 network_services: [
82 {"port": 22, "username": "root", "password": "root"}]
83 - DockerStrategy: {}
84 - SSHDriver:
85 keyfile: ""
86 """
87 )
88 return Environment(str(p))
89
90
91 @pytest.fixture
92 def docker_target(docker_env):
93 """Get a labgrid Target instance from the Environment instance
94 given by docker_env. When tearing down the Target instance, make sure
95 singleton ResourceManager is "reset".
96 """
97 t = docker_env.get_target()
98 yield t
99
100 # Fake! In real life, ResourceManager is intended to be a singleton.
101 # The class is created only once - when python parses common.py.
102 # But this means that the class with its "instances" attribute survives
103 # from test case to test case. This is not what we want. On the contrary,
104 # we want each of test_docker_with_daemon and test_docker_without_daemon
105 # to run with a *fresh* instance of the ResourceManager singleton.
106 #
107 # Luckily it is easy to "reset" ResourceManager. The singleton is kept
108 # in attribute "instances" so by resetting "instances" to {}, next test
109 # case will force creation of a fresh ResourceManager instance.
110 from labgrid.resource import ResourceManager
111
112 ResourceManager.instances = {}
113
114
115 @pytest.fixture
116 def command(docker_target):
117 """Bring system to a state where it's possible to execute commands
118 on a running docker container. When done, stop the container again.
119 """
120 strategy = docker_target.get_driver("DockerStrategy")
121 strategy.transition("accessible")
122 shell = docker_target.get_driver("CommandProtocol")
123 yield shell
124 strategy.transition("gone")
125
126
127 @pytest.fixture
128 def docker_target_for_local_image(docker_env_for_local_container):
129 """Same as `docker_target` but uses a different image uri"""
130 t = docker_env_for_local_container.get_target()
131 yield t
132
133 from labgrid.resource import ResourceManager
134
135 ResourceManager.instances = {}
136
137
138 @pytest.fixture
139 def local_command(docker_target_for_local_image):
140 """Same as `command` but uses a different image uri"""
141 strategy = docker_target_for_local_image.get_driver("DockerStrategy")
142 strategy.transition("accessible")
143 shell = docker_target_for_local_image.get_driver("CommandProtocol")
144 yield shell
145 strategy.transition("gone")
146
147
148 @pytest.mark.skipif(not check_external_progs_present(), reason="No access to a docker daemon")
149 def test_docker_with_daemon(command):
150 """Test the docker machinery when a running docker daemon can be used
151 (thus test is skipped if there is no such daemon). The tests executes
152 a few tests inside a running docker container using SSHDriver for access.
153 """
154 stdout, stderr, return_code = command.run("cat /proc/version")
155 assert return_code == 0
156 assert len(stdout) > 0
157 assert len(stderr) == 0
158 assert "Linux" in stdout[0]
159
160 stdout, stderr, return_code = command.run("false")
161 assert return_code != 0
162 assert len(stdout) == 0
163 assert len(stderr) == 0
164
165
166 @pytest.fixture
167 def build_image():
168 import docker
169
170 client = docker.from_env()
171 dockerfile_content = """
172 FROM rastasheep/ubuntu-sshd:16.04
173 """
174 dockerfile_stream = io.BytesIO(dockerfile_content.encode("utf-8"))
175 image, logs = client.images.build(fileobj=dockerfile_stream, tag="local_rastasheep", rm=True)
176
177
178 @pytest.mark.skipif(not check_external_progs_present(), reason="No access to a docker daemon")
179 def test_docker_with_daemon_and_local_image(build_image, local_command):
180 """Build a container locally and connect to it"""
181 stdout, stderr, return_code = local_command.run("cat /proc/version")
182 assert return_code == 0
183 assert len(stdout) > 0
184 assert len(stderr) == 0
185 assert "Linux" in stdout[0]
186
187 stdout, stderr, return_code = local_command.run("false")
188 assert return_code != 0
189 assert len(stdout) == 0
190 assert len(stderr) == 0
191
192
193 def test_create_driver_fail_missing_docker_daemon(target):
194 """The test target does not contain any DockerDaemon instance -
195 and so creation must fail.
196 """
197 with pytest.raises(NoResourceFoundError):
198 DockerDriver(target, "docker_driver")
199
200
201 def test_docker_without_daemon(docker_env, mocker):
202 """Test as many aspects as possible of DockerDriver, DockerDaemon,
203 DockerManager and DockerStrategy without using an actual
204 docker daemon, real sockets or system time"""
205
206 import docker
207
208 # Target::update_resources() and Target::await_resources use
209 # time.monotonic() and time.sleep() to control when to search
210 # for resources. Avoid time delays and make running from cmd-line
211 # and inside debugger equal by mocking out all time.
212 time_monotonic = mocker.patch("labgrid.target.monotonic")
213 time_monotonic.side_effect = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
214
215 # Mock actions on the imported "docker" python module
216 docker_client_class = mocker.patch("docker.DockerClient", autospec=True)
217 docker_client = docker_client_class.return_value
218 api_client_class = mocker.patch("docker.api.client.APIClient", autospec=True)
219 docker_client.api = api_client_class.return_value
220 api_client = docker_client.api
221 api_client.base_url = "unix:///var/run/docker.sock"
222 # First, a "mocked" old docker container is returned by
223 # ...api.containers(); this is done when DockerDaemon tries
224 # to clean up old containers. Next, a one-item list is delivered by
225 # ...api.containers() which is part of DockerDaemon::update_resources()
226 # - it is cached for future use; therefore no need to replicate
227 # this entry in the side_effects list.
228 api_client.containers.side_effect = [
229 [
230 {
231 "Labels": {DockerConstants.DOCKER_LG_CLEANUP_LABEL: DockerConstants.DOCKER_LG_CLEANUP_TYPE_AUTO},
232 "NetworkSettings": {"IPAddress": "1.1.1.1"},
233 "Names": "old-one",
234 "Id": "0",
235 }
236 ],
237 [
238 {
239 "Labels": {DockerConstants.DOCKER_LG_CLEANUP_LABEL: DockerConstants.DOCKER_LG_CLEANUP_TYPE_AUTO},
240 "NetworkSettings": {"IPAddress": "2.1.1.1"},
241 "Names": "actual-one",
242 "Id": "1",
243 }
244 ],
245 ]
246 docker_client.images.get.side_effect = docker.errors.ImageNotFound(
247 "Image not found", response=None, explanation=""
248 )
249
250 # Mock actions on the imported "socket" python module
251 socket_create_connection = mocker.patch("socket.create_connection")
252 sock = mocker.MagicMock()
253 # First two negative connection setup attempts are used at initial
254 # resource setup during strategy.transition("shell"); these simulate
255 # that it takes time for the docker container to come up. The final,
256 # successful, return value is delivered when t.update_resources()
257 # is called explicitly later on.
258 socket_create_connection.side_effect = [
259 Exception("No connection on first call"),
260 Exception("No connection on second call"),
261 sock,
262 ]
263
264 # get_target() - which calls make_target() - creates resources/drivers
265 # from .yaml configured environment. Creation provokes binding
266 # and attempts to connect to network services.
267 api_client.remove_container.assert_not_called()
268 t = docker_env.get_target()
269 assert api_client.remove_container.call_count == 1
270
271 # Make sure DockerDriver didn't accidentally succeed with a socket connect
272 # attempt (this fact is actually expressed by what happens next -
273 # the socket is closed).
274 sock.shutdown.assert_not_called()
275 sock.close.assert_not_called()
276
277 # Get strategy - needed to transition to "shell" state.
278 strategy = t.get_driver("DockerStrategy")
279
280 # strategy starts in state "unknown" so the following should be a no-op.
281 strategy.transition("unknown")
282
283 # Now activate DockerDriver and set it "on". This creates and starts
284 # a (mocked) container.
285 strategy.transition("accessible")
286
287 # Assert what mock calls transitioning to "shell" must have caused
288 #
289 # DockerDriver::on_activate():
290 image_uri = t.get_driver("DockerDriver").image_uri
291 docker_client.images.get.assert_called_once_with(image_uri)
292 docker_client.images.pull.assert_called_once_with(image_uri)
293
294 assert api_client.create_host_config.call_count == 1
295 assert api_client.create_container.call_count == 1
296 #
297 # DockerDriver::on()
298 assert api_client.start.call_count == 1
299
300 # From here the test using the real docker daemon would proceed with
301 # shell = t.get_driver('CommandProtocol')
302 # shell.run('...')
303 # which makes use of e.g. the SSHDriver. Binding the SSHDriver
304 # is important since it triggers activation of the NetworkService.
305 # But then SSHDriver uses ssh to connect to the NetworkService
306 # which will lead to error. Instead just call update_resources()
307 # directly - which is what is needed to provoke DockerDaemon to create
308 # a new NetworkService instance.
309 t.update_resources()
310
311 # This time socket connection was successful
312 # (per the third socket_create_connection return value defined above).
313 assert sock.shutdown.call_count == 1
314 assert sock.close.call_count == 1
315
316 # Bonus: Test what happens if taking a forbidden strategy transition:
317 # "shell" -> "unknown".
318 from labgrid.strategy import StrategyError
319
320 with pytest.raises(StrategyError):
321 strategy.transition("unknown")
322
323 # test and reset broken state
324 assert isinstance(strategy.broken, StrategyError)
325 strategy.broken = None
326
327 # Also bonus: How are invalid state names handled?
328 with pytest.raises(StrategyError):
329 strategy.transition("this is not a valid state")
330
331 # test and reset broken state
332 assert isinstance(strategy.broken, KeyError)
333 strategy.broken = None
334
335 # Return to "gone" state - to also use that part of the DockerDriver code.
336 strategy.transition("gone")
337 from labgrid.strategy.dockerstrategy import Status
338
339 assert strategy.status == Status.gone