Debian Codegraph @

ansible_collections/community/docker/plugins/connection/docker.py

raw
1 # Based on the chroot connection plugin by Maykel Moya
2 #
3 # (c) 2014, Lorin Hochstein
4 # (c) 2015, Leendert Brouwer (https://github.com/objectified)
5 # (c) 2015, Toshio Kuratomi <[email protected]>
6 # Copyright (c) 2017 Ansible Project
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 author:
14 - Lorin Hochestein (!UNKNOWN)
15 - Leendert Brouwer (!UNKNOWN)
16 name: docker
17 short_description: Run tasks in docker containers
18 description:
19 - Run commands or put/fetch files to an existing docker container.
20 - Uses the Docker CLI to execute commands in the container. If you prefer to directly connect to the Docker daemon, use
21 the P(community.docker.docker_api#connection) connection plugin.
22 options:
23 remote_addr:
24 description:
25 - The name of the container you want to access.
26 default: inventory_hostname
27 vars:
28 - name: inventory_hostname
29 - name: ansible_host
30 - name: ansible_docker_host
31 remote_user:
32 description:
33 - The user to execute as inside the container.
34 - If Docker is too old to allow this (< 1.7), the one set by Docker itself will be used.
35 vars:
36 - name: ansible_user
37 - name: ansible_docker_user
38 ini:
39 - section: defaults
40 key: remote_user
41 env:
42 - name: ANSIBLE_REMOTE_USER
43 cli:
44 - name: user
45 keyword:
46 - name: remote_user
47 docker_extra_args:
48 description:
49 - Extra arguments to pass to the docker command line.
50 default: ''
51 vars:
52 - name: ansible_docker_extra_args
53 ini:
54 - section: docker_connection
55 key: extra_cli_args
56 container_timeout:
57 default: 10
58 description:
59 - Controls how long we can wait to access reading output from the container once execution started.
60 env:
61 - name: ANSIBLE_TIMEOUT
62 - name: ANSIBLE_DOCKER_TIMEOUT
63 version_added: 2.2.0
64 ini:
65 - key: timeout
66 section: defaults
67 - key: timeout
68 section: docker_connection
69 version_added: 2.2.0
70 vars:
71 - name: ansible_docker_timeout
72 version_added: 2.2.0
73 cli:
74 - name: timeout
75 type: integer
76 extra_env:
77 description:
78 - Provide extra environment variables to set when running commands in the Docker container.
79 - This option can currently only be provided as Ansible variables due to limitations of ansible-core's configuration
80 manager.
81 vars:
82 - name: ansible_docker_extra_env
83 type: dict
84 version_added: 3.12.0
85 working_dir:
86 description:
87 - The directory inside the container to run commands in.
88 - Requires Docker CLI version 18.06 or later.
89 env:
90 - name: ANSIBLE_DOCKER_WORKING_DIR
91 ini:
92 - key: working_dir
93 section: docker_connection
94 vars:
95 - name: ansible_docker_working_dir
96 type: string
97 version_added: 3.12.0
98 privileged:
99 description:
100 - Whether commands should be run with extended privileges.
101 - B(Note) that this allows command to potentially break out of the container. Use with care!
102 env:
103 - name: ANSIBLE_DOCKER_PRIVILEGED
104 ini:
105 - key: privileged
106 section: docker_connection
107 vars:
108 - name: ansible_docker_privileged
109 type: boolean
110 default: false
111 version_added: 3.12.0
112 """
113
114 import fcntl
115 import os
116 import os.path
117 import re
118 import selectors
119 import subprocess
120 import typing as t
121 from shlex import quote
122
123 from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleFileNotFound
124 from ansible.module_utils.common.process import get_bin_path
125 from ansible.module_utils.common.text.converters import to_bytes, to_text
126 from ansible.plugins.connection import BUFSIZE, ConnectionBase
127 from ansible.utils.display import Display
128
129 from ansible_collections.community.docker.plugins.module_utils._version import (
130 LooseVersion,
131 )
132
133 display = Display()
134
135
136 class Connection(ConnectionBase):
137 """Local docker based connections"""
138
139 transport = "community.docker.docker"
140 has_pipelining = True
141
142 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
143 super().__init__(*args, **kwargs)
144
145 # Note: docker supports running as non-root in some configurations.
146 # (For instance, setting the UNIX socket file to be readable and
147 # writable by a specific UNIX group and then putting users into that
148 # group). Therefore we do not check that the user is root when using
149 # this connection. But if the user is getting a permission denied
150 # error it probably means that docker on their system is only
151 # configured to be connected to by root and they are not running as
152 # root.
153
154 self._docker_args: list[bytes | str] = []
155 self._container_user_cache: dict[str, str | None] = {}
156 self._version: str | None = None
157 self.remote_user: str | None = None
158 self.timeout: int | float | None = None
159
160 # Windows uses Powershell modules
161 if getattr(self._shell, "_IS_WINDOWS", False):
162 self.module_implementation_preferences = (".ps1", ".exe", "")
163
164 if "docker_command" in kwargs:
165 self.docker_cmd = kwargs["docker_command"]
166 else:
167 try:
168 self.docker_cmd = get_bin_path("docker")
169 except ValueError as exc:
170 raise AnsibleError("docker command not found in PATH") from exc
171
172 @staticmethod
173 def _sanitize_version(version: str) -> str:
174 version = re.sub("[^0-9a-zA-Z.]", "", version)
175 version = re.sub("^v", "", version)
176 return version
177
178 def _old_docker_version(self) -> tuple[list[str], str, bytes, int]:
179 cmd_args = self._docker_args
180
181 old_version_subcommand = ["version"]
182
183 old_docker_cmd = [self.docker_cmd] + cmd_args + old_version_subcommand
184 with subprocess.Popen(
185 old_docker_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
186 ) as p:
187 cmd_output, err = p.communicate()
188
189 return old_docker_cmd, to_text(cmd_output), err, p.returncode
190
191 def _new_docker_version(self) -> tuple[list[str], str, bytes, int]:
192 # no result yet, must be newer Docker version
193 cmd_args = self._docker_args
194
195 new_version_subcommand = ["version", "--format", "'{{.Server.Version}}'"]
196
197 new_docker_cmd = [self.docker_cmd] + cmd_args + new_version_subcommand
198 with subprocess.Popen(
199 new_docker_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
200 ) as p:
201 cmd_output, err = p.communicate()
202 return new_docker_cmd, to_text(cmd_output), err, p.returncode
203
204 def _get_docker_version(self) -> str:
205 cmd, cmd_output, err, returncode = self._old_docker_version()
206 if returncode == 0:
207 for line in to_text(cmd_output, errors="surrogate_or_strict").split("\n"):
208 if line.startswith("Server version:"): # old docker versions
209 return self._sanitize_version(line.split()[2])
210
211 cmd, cmd_output, err, returncode = self._new_docker_version()
212 if returncode:
213 raise AnsibleError(
214 f"Docker version check ({to_text(cmd)}) failed: {to_text(err)}"
215 )
216
217 return self._sanitize_version(to_text(cmd_output, errors="surrogate_or_strict"))
218
219 def _get_docker_remote_user(self) -> str | None:
220 """Get the default user configured in the docker container"""
221 container = self.get_option("remote_addr")
222 if container in self._container_user_cache:
223 return self._container_user_cache[container]
224 with subprocess.Popen(
225 [self.docker_cmd, "inspect", "--format", "{{.Config.User}}", container],
226 stdout=subprocess.PIPE,
227 stderr=subprocess.PIPE,
228 ) as p:
229 out_b, err_b = p.communicate()
230 out = to_text(out_b, errors="surrogate_or_strict")
231
232 if p.returncode != 0:
233 display.warning(
234 f"unable to retrieve default user from docker container: {out} {to_text(err_b)}"
235 )
236 self._container_user_cache[container] = None
237 return None
238
239 # The default exec user is root, unless it was changed in the Dockerfile with USER
240 user = out.strip() or "root"
241 self._container_user_cache[container] = user
242 return user
243
244 def _build_exec_cmd(self, cmd: list[bytes | str]) -> list[bytes | str]:
245 """Build the local docker exec command to run cmd on remote_host
246
247 If remote_user is available and is supported by the docker
248 version we are using, it will be provided to docker exec.
249 """
250
251 local_cmd = [self.docker_cmd]
252
253 if self._docker_args:
254 local_cmd += self._docker_args
255
256 local_cmd += [b"exec"]
257
258 if self.remote_user is not None:
259 local_cmd += [b"-u", self.remote_user]
260
261 if self.get_option("extra_env"):
262 for k, v in self.get_option("extra_env").items():
263 for val, what in ((k, "Key"), (v, "Value")):
264 if not isinstance(val, str):
265 raise AnsibleConnectionFailure(
266 f"Non-string {what.lower()} found for extra_env option. Ambiguous env options must be "
267 "wrapped in quotes to avoid them being interpreted when directly specified "
268 "in YAML, or explicitly converted to strings when the option is templated. "
269 f"{what}: {val!r}"
270 )
271 local_cmd += [
272 b"-e",
273 b"%s=%s"
274 % (
275 to_bytes(k, errors="surrogate_or_strict"),
276 to_bytes(v, errors="surrogate_or_strict"),
277 ),
278 ]
279
280 if self.get_option("working_dir") is not None:
281 local_cmd += [
282 b"-w",
283 to_bytes(self.get_option("working_dir"), errors="surrogate_or_strict"),
284 ]
285 if self.docker_version != "dev" and LooseVersion(
286 self.docker_version
287 ) < LooseVersion("18.06"):
288 # https://github.com/docker/cli/pull/732, first appeared in release 18.06.0
289 raise AnsibleConnectionFailure(
290 f"Providing the working directory requires Docker CLI version 18.06 or newer. You have Docker CLI version {self.docker_version}."
291 )
292
293 if self.get_option("privileged"):
294 local_cmd += [b"--privileged"]
295
296 # -i is needed to keep stdin open which allows pipelining to work
297 local_cmd += [b"-i", self.get_option("remote_addr")] + cmd
298
299 return local_cmd
300
301 def _set_docker_args(self) -> None:
302 # TODO: this is mostly for backwards compatibility, play_context is used as fallback for older versions
303 # docker arguments
304 del self._docker_args[:]
305 extra_args = self.get_option("docker_extra_args") or getattr(
306 self._play_context, "docker_extra_args", ""
307 )
308 if extra_args:
309 self._docker_args += extra_args.split(" ")
310
311 def _set_conn_data(self) -> None:
312 """initialize for the connection, cannot do only in init since all data is not ready at that point"""
313
314 self._set_docker_args()
315
316 self.remote_user = self.get_option("remote_user")
317 if self.remote_user is None and self._play_context.remote_user is not None:
318 self.remote_user = self._play_context.remote_user
319
320 # timeout, use unless default and pc is different, backwards compat
321 self.timeout = self.get_option("container_timeout")
322 if self.timeout == 10 and self.timeout != self._play_context.timeout:
323 self.timeout = self._play_context.timeout
324
325 @property
326 def docker_version(self) -> str:
327 if not self._version:
328 self._set_docker_args()
329
330 self._version = self._get_docker_version()
331 if self._version == "dev":
332 display.warning(
333 'Docker version number is "dev". Will assume latest version.'
334 )
335 if self._version != "dev" and LooseVersion(self._version) < LooseVersion(
336 "1.3"
337 ):
338 raise AnsibleError(
339 "docker connection type requires docker 1.3 or higher"
340 )
341 return self._version
342
343 def _get_actual_user(self) -> str | None:
344 if self.remote_user is not None:
345 # An explicit user is provided
346 if self.docker_version == "dev" or LooseVersion(
347 self.docker_version
348 ) >= LooseVersion("1.7"):
349 # Support for specifying the exec user was added in docker 1.7
350 return self.remote_user
351 self.remote_user = None
352 actual_user = self._get_docker_remote_user()
353 if actual_user != self.get_option("remote_user"):
354 display.warning(
355 f"docker {self.docker_version} does not support remote_user, using container default: {actual_user or '?'}"
356 )
357 return actual_user
358 if self._display.verbosity > 2:
359 # Since we are not setting the actual_user, look it up so we have it for logging later
360 # Only do this if display verbosity is high enough that we'll need the value
361 # This saves overhead from calling into docker when we do not need to.
362 return self._get_docker_remote_user()
363 return None
364
365 def _connect(self) -> t.Self:
366 """Connect to the container. Nothing to do"""
367 super()._connect() # type: ignore[safe-super]
368 if not self._connected:
369 self._set_conn_data()
370 actual_user = self._get_actual_user()
371 display.vvv(
372 f"ESTABLISH DOCKER CONNECTION FOR USER: {actual_user or '?'}",
373 host=self.get_option("remote_addr"),
374 )
375 self._connected = True
376 return self
377
378 def exec_command(
379 self, cmd: str, in_data: bytes | None = None, sudoable: bool = False
380 ) -> tuple[int, bytes, bytes]:
381 """Run a command on the docker host"""
382
383 self._set_conn_data()
384
385 super().exec_command(cmd, in_data=in_data, sudoable=sudoable) # type: ignore[safe-super]
386
387 local_cmd = self._build_exec_cmd([self._play_context.executable, "-c", cmd])
388
389 display.vvv(f"EXEC {to_text(local_cmd)}", host=self.get_option("remote_addr"))
390 display.debug("opening command with Popen()")
391
392 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
393
394 with subprocess.Popen(
395 local_cmd,
396 stdin=subprocess.PIPE,
397 stdout=subprocess.PIPE,
398 stderr=subprocess.PIPE,
399 ) as p:
400 assert p.stdin is not None
401 assert p.stdout is not None
402 assert p.stderr is not None
403 display.debug("done running command with Popen()")
404
405 if self.become and self.become.expect_prompt() and sudoable:
406 fcntl.fcntl(
407 p.stdout,
408 fcntl.F_SETFL,
409 fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK,
410 )
411 fcntl.fcntl(
412 p.stderr,
413 fcntl.F_SETFL,
414 fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK,
415 )
416 selector = selectors.DefaultSelector()
417 selector.register(p.stdout, selectors.EVENT_READ)
418 selector.register(p.stderr, selectors.EVENT_READ)
419
420 become_output = b""
421 try:
422 while not self.become.check_success(
423 become_output
424 ) and not self.become.check_password_prompt(become_output):
425 events = selector.select(self.timeout)
426 if not events:
427 stdout, stderr = p.communicate()
428 raise AnsibleError(
429 "timeout waiting for privilege escalation password prompt:\n"
430 + to_text(become_output)
431 )
432
433 chunks = b""
434 for key, dummy_event in events:
435 if key.fileobj == p.stdout:
436 chunk = p.stdout.read()
437 if chunk:
438 chunks += chunk
439 elif key.fileobj == p.stderr:
440 chunk = p.stderr.read()
441 if chunk:
442 chunks += chunk
443
444 if not chunks:
445 stdout, stderr = p.communicate()
446 raise AnsibleError(
447 "privilege output closed while waiting for password prompt:\n"
448 + to_text(become_output)
449 )
450 become_output += chunks
451 finally:
452 selector.close()
453
454 if not self.become.check_success(become_output):
455 become_pass = self.become.get_option(
456 "become_pass", playcontext=self._play_context
457 )
458 p.stdin.write(
459 to_bytes(become_pass, errors="surrogate_or_strict") + b"\n"
460 )
461 fcntl.fcntl(
462 p.stdout,
463 fcntl.F_SETFL,
464 fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK,
465 )
466 fcntl.fcntl(
467 p.stderr,
468 fcntl.F_SETFL,
469 fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK,
470 )
471
472 display.debug("getting output with communicate()")
473 stdout, stderr = p.communicate(in_data)
474 display.debug("done communicating")
475
476 display.debug("done with docker.exec_command()")
477 return (p.returncode, stdout, stderr)
478
479 def _prefix_login_path(self, remote_path: str) -> str:
480 """Make sure that we put files into a standard path
481
482 If a path is relative, then we need to choose where to put it.
483 ssh chooses $HOME but we are not guaranteed that a home dir will
484 exist in any given chroot. So for now we are choosing "/" instead.
485 This also happens to be the former default.
486
487 Can revisit using $HOME instead if it is a problem
488 """
489 if getattr(self._shell, "_IS_WINDOWS", False):
490 import ntpath
491
492 return ntpath.normpath(remote_path)
493 if not remote_path.startswith(os.path.sep):
494 remote_path = os.path.join(os.path.sep, remote_path)
495 return os.path.normpath(remote_path)
496
497 def put_file(self, in_path: str, out_path: str) -> None:
498 """Transfer a file from local to docker container"""
499 self._set_conn_data()
500 super().put_file(in_path, out_path) # type: ignore[safe-super]
501 display.vvv(f"PUT {in_path} TO {out_path}", host=self.get_option("remote_addr"))
502
503 out_path = self._prefix_login_path(out_path)
504 if not os.path.exists(to_bytes(in_path, errors="surrogate_or_strict")):
505 raise AnsibleFileNotFound(
506 f"file or module does not exist: {to_text(in_path)}"
507 )
508
509 out_path = quote(out_path)
510 # Older docker does not have native support for copying files into
511 # running containers, so we use docker exec to implement this
512 # Although docker version 1.8 and later provide support, the
513 # owner and group of the files are always set to root
514 with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
515 if not os.fstat(in_file.fileno()).st_size:
516 count = " count=0"
517 else:
518 count = ""
519 args = self._build_exec_cmd(
520 [
521 self._play_context.executable,
522 "-c",
523 f"dd of={out_path} bs={BUFSIZE}{count}",
524 ]
525 )
526 args = [to_bytes(i, errors="surrogate_or_strict") for i in args]
527 try:
528 # pylint: disable-next=consider-using-with
529 p = subprocess.Popen(
530 args, stdin=in_file, stdout=subprocess.PIPE, stderr=subprocess.PIPE
531 )
532 except OSError as exc:
533 raise AnsibleError(
534 "docker connection requires dd command in the container to put files"
535 ) from exc
536 stdout, stderr = p.communicate()
537
538 if p.returncode != 0:
539 raise AnsibleError(
540 f"failed to transfer file {to_text(in_path)} to {to_text(out_path)}:\n{to_text(stdout)}\n{to_text(stderr)}"
541 )
542
543 def fetch_file(self, in_path: str, out_path: str) -> None:
544 """Fetch a file from container to local."""
545 self._set_conn_data()
546 super().fetch_file(in_path, out_path) # type: ignore[safe-super]
547 display.vvv(
548 f"FETCH {in_path} TO {out_path}", host=self.get_option("remote_addr")
549 )
550
551 in_path = self._prefix_login_path(in_path)
552 # out_path is the final file path, but docker takes a directory, not a
553 # file path
554 out_dir = os.path.dirname(out_path)
555
556 args = [
557 self.docker_cmd,
558 "cp",
559 f"{self.get_option('remote_addr')}:{in_path}",
560 out_dir,
561 ]
562 args = [to_bytes(i, errors="surrogate_or_strict") for i in args]
563
564 with subprocess.Popen(
565 args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
566 ) as p:
567 p.communicate()
568
569 if getattr(self._shell, "_IS_WINDOWS", False):
570 import ntpath
571
572 actual_out_path = ntpath.join(out_dir, ntpath.basename(in_path))
573 else:
574 actual_out_path = os.path.join(out_dir, os.path.basename(in_path))
575
576 if p.returncode != 0:
577 # Older docker does not have native support for fetching files command `cp`
578 # If `cp` fails, try to use `dd` instead
579 args = self._build_exec_cmd(
580 [
581 self._play_context.executable,
582 "-c",
583 f"dd if={in_path} bs={BUFSIZE}",
584 ]
585 )
586 args = [to_bytes(i, errors="surrogate_or_strict") for i in args]
587 with open(
588 to_bytes(actual_out_path, errors="surrogate_or_strict"), "wb"
589 ) as out_file:
590 try:
591 # pylint: disable-next=consider-using-with
592 pp = subprocess.Popen(
593 args,
594 stdin=subprocess.PIPE,
595 stdout=out_file,
596 stderr=subprocess.PIPE,
597 )
598 except OSError as exc:
599 raise AnsibleError(
600 "docker connection requires dd command in the container to put files"
601 ) from exc
602 stdout, stderr = pp.communicate()
603
604 if pp.returncode != 0:
605 raise AnsibleError(
606 f"failed to fetch file {in_path} to {out_path}:\n{stdout!r}\n{stderr!r}"
607 )
608
609 # Rename if needed
610 if actual_out_path != out_path:
611 os.rename(
612 to_bytes(actual_out_path, errors="strict"),
613 to_bytes(out_path, errors="strict"),
614 )
615
616 def close(self) -> None:
617 """Terminate the connection. Nothing to do for Docker"""
618 super().close() # type: ignore[safe-super]
619 self._connected = False
620
621 def reset(self) -> None:
622 # Clear container user cache
623 self._container_user_cache = {}