Debian Codegraph @

tests/test_docker.py

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