Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_copy.py

raw
1 # Copyright 2016 Red Hat | Ansible
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import base64
11 import datetime
12 import io
13 import json
14 import os
15 import os.path
16 import shutil
17 import stat
18 import tarfile
19 import typing as t
20
21 from ansible.module_utils.common.text.converters import to_bytes, to_text
22
23 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
24 APIError,
25 NotFound,
26 )
27
28 if t.TYPE_CHECKING:
29 from collections.abc import Callable
30
31 from _typeshed import WriteableBuffer
32
33 from ansible_collections.community.docker.plugins.module_utils._api.api.client import (
34 APIClient,
35 )
36
37
38 class DockerFileCopyError(Exception):
39 pass
40
41
42 class DockerUnexpectedError(DockerFileCopyError):
43 pass
44
45
46 class DockerFileNotFound(DockerFileCopyError):
47 pass
48
49
50 def _put_archive(
51 client: APIClient, container: str, path: str, data: bytes | t.Generator[bytes]
52 ) -> bool:
53 # data can also be file object for streaming. This is because _put uses requests's put().
54 # See https://requests.readthedocs.io/en/latest/user/advanced/#streaming-uploads
55 url = client._url("/containers/{0}/archive", container)
56 res = client._put(url, params={"path": path}, data=data)
57 client._raise_for_status(res)
58 return res.status_code == 200
59
60
61 def _symlink_tar_creator(
62 b_in_path: bytes,
63 file_stat: os.stat_result,
64 out_file: str | bytes,
65 user_id: int,
66 group_id: int,
67 mode: int | None = None,
68 user_name: str | None = None,
69 ) -> bytes:
70 if not stat.S_ISLNK(file_stat.st_mode):
71 raise DockerUnexpectedError("stat information is not for a symlink")
72 bio = io.BytesIO()
73 with tarfile.open(
74 fileobj=bio, mode="w|", dereference=False, encoding="utf-8"
75 ) as tar:
76 # Note that without both name (bytes) and arcname (unicode), this either fails for
77 # Python 2.7, Python 3.5/3.6, or Python 3.7+. Only when passing both (in this
78 # form) it works with Python 2.7, 3.5, 3.6, and 3.7 up to 3.11
79 tarinfo = tar.gettarinfo(b_in_path, arcname=to_text(out_file))
80 tarinfo.uid = user_id
81 tarinfo.uname = ""
82 if user_name:
83 tarinfo.uname = user_name
84 tarinfo.gid = group_id
85 tarinfo.gname = ""
86 tarinfo.mode &= 0o700
87 if mode is not None:
88 tarinfo.mode = mode
89 if not tarinfo.issym():
90 raise DockerUnexpectedError("stat information is not for a symlink")
91 tar.addfile(tarinfo)
92 return bio.getvalue()
93
94
95 def _symlink_tar_generator(
96 b_in_path: bytes,
97 file_stat: os.stat_result,
98 out_file: str | bytes,
99 user_id: int,
100 group_id: int,
101 mode: int | None = None,
102 user_name: str | None = None,
103 ) -> t.Generator[bytes]:
104 yield _symlink_tar_creator(
105 b_in_path, file_stat, out_file, user_id, group_id, mode, user_name
106 )
107
108
109 def _regular_file_tar_generator(
110 b_in_path: bytes,
111 file_stat: os.stat_result,
112 out_file: str | bytes,
113 user_id: int,
114 group_id: int,
115 mode: int | None = None,
116 user_name: str | None = None,
117 ) -> t.Generator[bytes]:
118 if not stat.S_ISREG(file_stat.st_mode):
119 raise DockerUnexpectedError("stat information is not for a regular file")
120 tarinfo = tarfile.TarInfo()
121 tarinfo.name = (
122 os.path.splitdrive(to_text(out_file))[1].replace(os.sep, "/").lstrip("/")
123 )
124 tarinfo.mode = (file_stat.st_mode & 0o700) if mode is None else mode
125 tarinfo.uid = user_id
126 tarinfo.gid = group_id
127 tarinfo.size = file_stat.st_size
128 tarinfo.mtime = file_stat.st_mtime
129 tarinfo.type = tarfile.REGTYPE
130 tarinfo.linkname = ""
131 if user_name:
132 tarinfo.uname = user_name
133
134 tarinfo_buf = tarinfo.tobuf()
135 total_size = len(tarinfo_buf)
136 yield tarinfo_buf
137
138 size = tarinfo.size
139 total_size += size
140 with open(b_in_path, "rb") as f:
141 while size > 0:
142 to_read = min(size, 65536)
143 buf = f.read(to_read)
144 if not buf:
145 break
146 size -= len(buf)
147 yield buf
148 if size:
149 # If for some reason the file shrunk, fill up to the announced size with zeros.
150 # (If it enlarged, ignore the remainder.)
151 yield tarfile.NUL * size
152
153 remainder = tarinfo.size % tarfile.BLOCKSIZE
154 if remainder:
155 # We need to write a multiple of 512 bytes. Fill up with zeros.
156 yield tarfile.NUL * (tarfile.BLOCKSIZE - remainder)
157 total_size += tarfile.BLOCKSIZE - remainder
158
159 # End with two zeroed blocks
160 yield tarfile.NUL * (2 * tarfile.BLOCKSIZE)
161 total_size += 2 * tarfile.BLOCKSIZE
162
163 remainder = total_size % tarfile.RECORDSIZE
164 if remainder > 0:
165 yield tarfile.NUL * (tarfile.RECORDSIZE - remainder)
166
167
168 def _regular_content_tar_generator(
169 content: bytes,
170 out_file: str | bytes,
171 user_id: int,
172 group_id: int,
173 mode: int,
174 user_name: str | None = None,
175 ) -> t.Generator[bytes]:
176 tarinfo = tarfile.TarInfo()
177 tarinfo.name = (
178 os.path.splitdrive(to_text(out_file))[1].replace(os.sep, "/").lstrip("/")
179 )
180 tarinfo.mode = mode
181 tarinfo.uid = user_id
182 tarinfo.gid = group_id
183 tarinfo.size = len(content)
184 tarinfo.mtime = int(datetime.datetime.now().timestamp())
185 tarinfo.type = tarfile.REGTYPE
186 tarinfo.linkname = ""
187 if user_name:
188 tarinfo.uname = user_name
189
190 tarinfo_buf = tarinfo.tobuf()
191 total_size = len(tarinfo_buf)
192 yield tarinfo_buf
193
194 total_size += len(content)
195 yield content
196
197 remainder = tarinfo.size % tarfile.BLOCKSIZE
198 if remainder:
199 # We need to write a multiple of 512 bytes. Fill up with zeros.
200 yield tarfile.NUL * (tarfile.BLOCKSIZE - remainder)
201 total_size += tarfile.BLOCKSIZE - remainder
202
203 # End with two zeroed blocks
204 yield tarfile.NUL * (2 * tarfile.BLOCKSIZE)
205 total_size += 2 * tarfile.BLOCKSIZE
206
207 remainder = total_size % tarfile.RECORDSIZE
208 if remainder > 0:
209 yield tarfile.NUL * (tarfile.RECORDSIZE - remainder)
210
211
212 def put_file(
213 client: APIClient,
214 container: str,
215 in_path: str,
216 out_path: str,
217 user_id: int,
218 group_id: int,
219 mode: int | None = None,
220 user_name: str | None = None,
221 follow_links: bool = False,
222 ) -> None:
223 """Transfer a file from local to Docker container."""
224 if not os.path.exists(to_bytes(in_path, errors="surrogate_or_strict")):
225 raise DockerFileNotFound(f"file or module does not exist: {to_text(in_path)}")
226
227 b_in_path = to_bytes(in_path, errors="surrogate_or_strict")
228
229 out_dir, out_file = os.path.split(out_path)
230
231 if follow_links:
232 file_stat = os.stat(b_in_path)
233 else:
234 file_stat = os.lstat(b_in_path)
235
236 if stat.S_ISREG(file_stat.st_mode):
237 stream = _regular_file_tar_generator(
238 b_in_path,
239 file_stat,
240 out_file,
241 user_id,
242 group_id,
243 mode=mode,
244 user_name=user_name,
245 )
246 elif stat.S_ISLNK(file_stat.st_mode):
247 stream = _symlink_tar_generator(
248 b_in_path,
249 file_stat,
250 out_file,
251 user_id,
252 group_id,
253 mode=mode,
254 user_name=user_name,
255 )
256 else:
257 file_part = " referenced by" if follow_links else ""
258 raise DockerFileCopyError(
259 f"File{file_part} {in_path} is neither a regular file nor a symlink (stat mode {oct(file_stat.st_mode)})."
260 )
261
262 ok = _put_archive(client, container, out_dir, stream)
263 if not ok:
264 raise DockerUnexpectedError(
265 f'Unknown error while creating file "{out_path}" in container "{container}".'
266 )
267
268
269 def put_file_content(
270 client: APIClient,
271 container: str,
272 content: bytes,
273 out_path: str,
274 user_id: int,
275 group_id: int,
276 mode: int,
277 user_name: str | None = None,
278 ) -> None:
279 """Transfer a file from local to Docker container."""
280 out_dir, out_file = os.path.split(out_path)
281
282 stream = _regular_content_tar_generator(
283 content, out_file, user_id, group_id, mode, user_name=user_name
284 )
285
286 ok = _put_archive(client, container, out_dir, stream)
287 if not ok:
288 raise DockerUnexpectedError(
289 f'Unknown error while creating file "{out_path}" in container "{container}".'
290 )
291
292
293 def stat_file(
294 client: APIClient,
295 container: str,
296 in_path: str,
297 follow_links: bool = False,
298 log: Callable[[str], None] | None = None,
299 ) -> tuple[str, dict[str, t.Any] | None, str | None]:
300 """Fetch information on a file from a Docker container to local.
301
302 Return a tuple ``(path, stat_data, link_target)`` where:
303
304 :path: is the resolved path in case ``follow_links=True``;
305 :stat_data: is ``None`` if the file does not exist, or a dictionary with fields
306 ``name`` (string), ``size`` (integer), ``mode`` (integer, see https://pkg.go.dev/io/fs#FileMode),
307 ``mtime`` (string), and ``linkTarget`` (string);
308 :link_target: is ``None`` if the file is not a symlink or when ``follow_links=False``,
309 and a string with the symlink target otherwise.
310 """
311 considered_in_paths = set()
312
313 while True:
314 if in_path in considered_in_paths:
315 raise DockerFileCopyError(
316 f"Found infinite symbolic link loop when trying to stating {in_path!r}"
317 )
318 considered_in_paths.add(in_path)
319
320 if log:
321 log(f"FETCH: Stating {in_path!r}")
322
323 response = client._head(
324 client._url("/containers/{0}/archive", container),
325 params={"path": in_path},
326 )
327 if response.status_code == 404:
328 return in_path, None, None
329 client._raise_for_status(response)
330 header = response.headers.get("x-docker-container-path-stat")
331 try:
332 if header is None:
333 raise ValueError("x-docker-container-path-stat header not present")
334 stat_data = json.loads(base64.b64decode(header))
335 except Exception as exc:
336 raise DockerUnexpectedError(
337 f"When retrieving information for {in_path} from {container}, obtained header {header!r} that cannot be loaded as JSON: {exc}"
338 ) from exc
339
340 # https://pkg.go.dev/io/fs#FileMode: bit 32 - 5 means ModeSymlink
341 if stat_data["mode"] & (1 << (32 - 5)) != 0:
342 link_target = stat_data["linkTarget"]
343 if not follow_links:
344 return in_path, stat_data, link_target
345 in_path = os.path.join(os.path.split(in_path)[0], link_target)
346 continue
347
348 return in_path, stat_data, None
349
350
351 class _RawGeneratorFileobj(io.RawIOBase):
352 def __init__(self, stream: t.Generator[bytes]):
353 self._stream = stream
354 self._buf = b""
355
356 def readable(self) -> bool:
357 return True
358
359 def _readinto_from_buf(self, b: WriteableBuffer, index: int, length: int) -> int:
360 cpy = min(length - index, len(self._buf))
361 if cpy:
362 b[index : index + cpy] = self._buf[:cpy] # type: ignore # TODO!
363 self._buf = self._buf[cpy:]
364 index += cpy
365 return index
366
367 def readinto(self, b: WriteableBuffer) -> int:
368 index = 0
369 length = len(b) # type: ignore # TODO!
370
371 index = self._readinto_from_buf(b, index, length)
372 if index == length:
373 return index
374
375 try:
376 self._buf += next(self._stream)
377 except StopIteration:
378 return index
379
380 return self._readinto_from_buf(b, index, length)
381
382
383 def _stream_generator_to_fileobj(stream: t.Generator[bytes]) -> io.BufferedReader:
384 """Given a generator that generates chunks of bytes, create a readable buffered stream."""
385 raw = _RawGeneratorFileobj(stream)
386 return io.BufferedReader(raw)
387
388
389 _T = t.TypeVar("_T")
390
391
392 def fetch_file_ex(
393 client: APIClient,
394 container: str,
395 in_path: str,
396 process_none: Callable[[str], _T],
397 process_regular: Callable[[str, tarfile.TarFile, tarfile.TarInfo], _T],
398 process_symlink: Callable[[str, tarfile.TarInfo], _T],
399 process_other: Callable[[str, tarfile.TarInfo], _T],
400 follow_links: bool = False,
401 log: Callable[[str], None] | None = None,
402 ) -> _T:
403 """Fetch a file (as a tar file entry) from a Docker container to local."""
404 considered_in_paths: set[str] = set()
405
406 while True:
407 if in_path in considered_in_paths:
408 raise DockerFileCopyError(
409 f'Found infinite symbolic link loop when trying to fetch "{in_path}"'
410 )
411 considered_in_paths.add(in_path)
412
413 if log:
414 log(f'FETCH: Fetching "{in_path}"')
415 try:
416 stream = client.get_raw_stream(
417 "/containers/{0}/archive",
418 container,
419 params={"path": in_path},
420 headers={"Accept-Encoding": "identity"},
421 )
422 except NotFound:
423 return process_none(in_path)
424
425 with tarfile.open(
426 fileobj=_stream_generator_to_fileobj(stream), mode="r|"
427 ) as tar:
428 symlink_member: tarfile.TarInfo | None = None
429 result: _T | None = None
430 found = False
431 for member in tar:
432 if found:
433 raise DockerUnexpectedError(
434 "Received tarfile contains more than one file!"
435 )
436 found = True
437 if member.issym():
438 symlink_member = member
439 continue
440 if member.isfile():
441 result = process_regular(in_path, tar, member)
442 continue
443 result = process_other(in_path, member)
444 if symlink_member:
445 if not follow_links:
446 return process_symlink(in_path, symlink_member)
447 in_path = os.path.join(
448 os.path.split(in_path)[0], symlink_member.linkname
449 )
450 if log:
451 log(f'FETCH: Following symbolic link to "{in_path}"')
452 continue
453 if found:
454 return result # type: ignore
455 raise DockerUnexpectedError("Received tarfile is empty!")
456
457
458 def fetch_file(
459 client: APIClient,
460 container: str,
461 in_path: str,
462 out_path: str,
463 follow_links: bool = False,
464 log: Callable[[str], None] | None = None,
465 ) -> str:
466 b_out_path = to_bytes(out_path, errors="surrogate_or_strict")
467
468 def process_none(in_path: str) -> str:
469 raise DockerFileNotFound(
470 f"File {in_path} does not exist in container {container}"
471 )
472
473 def process_regular(
474 in_path: str, tar: tarfile.TarFile, member: tarfile.TarInfo
475 ) -> str:
476 if not follow_links and os.path.exists(b_out_path):
477 os.unlink(b_out_path)
478
479 reader = tar.extractfile(member)
480 if reader:
481 with reader as in_f, open(b_out_path, "wb") as out_f:
482 shutil.copyfileobj(in_f, out_f)
483 return in_path
484
485 def process_symlink(in_path: str, member: tarfile.TarInfo) -> str:
486 if os.path.exists(b_out_path):
487 os.unlink(b_out_path)
488
489 os.symlink(member.linkname, b_out_path)
490 return in_path
491
492 def process_other(in_path: str, member: tarfile.TarInfo) -> str:
493 raise DockerFileCopyError(
494 f'Remote file "{in_path}" is not a regular file or a symbolic link'
495 )
496
497 return fetch_file_ex(
498 client,
499 container,
500 in_path,
501 process_none,
502 process_regular,
503 process_symlink,
504 process_other,
505 follow_links=follow_links,
506 log=log,
507 )
508
509
510 def _execute_command(
511 client: APIClient,
512 container: str,
513 command: list[str],
514 log: Callable[[str], None] | None = None,
515 check_rc: bool = False,
516 ) -> tuple[int, bytes, bytes]:
517 if log:
518 log(f"Executing {command} in {container}")
519
520 data = {
521 "Container": container,
522 "User": "",
523 "Privileged": False,
524 "Tty": False,
525 "AttachStdin": False,
526 "AttachStdout": True,
527 "AttachStderr": True,
528 "Cmd": command,
529 }
530
531 if "detachKeys" in client._general_configs:
532 data["detachKeys"] = client._general_configs["detachKeys"]
533
534 try:
535 exec_data = client.post_json_to_json(
536 "/containers/{0}/exec", container, data=data
537 )
538 except NotFound as e:
539 raise DockerFileCopyError(f'Could not find container "{container}"') from e
540 except APIError as e:
541 if e.response is not None and e.response.status_code == 409:
542 raise DockerFileCopyError(
543 f'Cannot execute command in paused container "{container}"'
544 ) from e
545 raise
546 exec_id = exec_data["Id"]
547
548 data = {"Tty": False, "Detach": False}
549 stdout, stderr = client.post_json_to_stream(
550 "/exec/{0}/start", exec_id, stream=False, demux=True, tty=False
551 )
552
553 result = client.get_json("/exec/{0}/json", exec_id)
554
555 rc: int = result.get("ExitCode") or 0
556 stdout = stdout or b""
557 stderr = stderr or b""
558
559 if log:
560 log(f"Exit code {rc}, stdout {stdout!r}, stderr {stderr!r}")
561
562 if check_rc and rc != 0:
563 command_str = " ".join(command)
564 raise DockerUnexpectedError(
565 f'Obtained unexpected exit code {rc} when running "{command_str}" in {container}.\nSTDOUT: {stdout!r}\nSTDERR: {stderr!r}'
566 )
567
568 return rc, stdout, stderr
569
570
571 def determine_user_group(
572 client: APIClient, container: str, log: Callable[[str], None] | None = None
573 ) -> tuple[int, int]:
574 dummy_rc, stdout, dummy_stderr = _execute_command(
575 client, container, ["/bin/sh", "-c", "id -u && id -g"], check_rc=True, log=log
576 )
577
578 stdout_lines = stdout.splitlines()
579 if len(stdout_lines) != 2:
580 raise DockerUnexpectedError(
581 f"Expected two-line output to obtain user and group ID for container {container}, but got {len(stdout_lines)} lines:\n{stdout!r}"
582 )
583
584 user_id, group_id = stdout_lines
585 try:
586 return int(user_id), int(group_id)
587 except ValueError as exc:
588 raise DockerUnexpectedError(
589 f"Expected two-line output with numeric IDs to obtain user and group ID for container {container}, but got {user_id!r} and {group_id!r} instead"
590 ) from exc