Debian Codegraph @

ansible_collections/community/general/plugins/modules/archive.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Ben Doherty <[email protected]>
4 # Sponsored by Oomph, Inc. http://www.oomphinc.com
5 # Copyright (c) 2017, Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: archive
13 short_description: Creates a compressed archive of one or more files or trees
14 extends_documentation_fragment:
15 - ansible.builtin.files
16 - community.general._attributes
17 description:
18 - Creates or extends an archive.
19 - The source and archive are on the target host, and the archive I(is not) copied to the controller host.
20 - Source files can be deleted after archival by specifying O(remove=True).
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 path:
28 description:
29 - Remote absolute path, glob, or list of paths or globs for the file or files to compress or archive.
30 type: list
31 elements: path
32 required: true
33 format:
34 description:
35 - The type of compression to use.
36 type: str
37 choices: [bz2, gz, tar, xz, zip]
38 default: gz
39 dest:
40 description:
41 - The file name of the destination archive. The parent directory must exists on the remote host.
42 - This is required when O(path) refers to multiple files by either specifying a glob, a directory or multiple paths
43 in a list.
44 - If the destination archive already exists, it is truncated and overwritten.
45 type: path
46 exclude_path:
47 description:
48 - Remote absolute path, glob, or list of paths or globs for the file or files to exclude from O(path) list and glob
49 expansion.
50 - Use O(exclusion_patterns) to instead exclude files or subdirectories below any of the paths from the O(path) list.
51 type: list
52 elements: path
53 default: []
54 exclusion_patterns:
55 description:
56 - Glob style patterns to exclude files or directories from the resulting archive.
57 - This differs from O(exclude_path) which applies only to the source paths from O(path).
58 type: list
59 elements: path
60 version_added: 3.2.0
61 force_archive:
62 description:
63 - Allows you to force the module to treat this as an archive even if only a single file is specified.
64 - By default when a single file is specified it is compressed only (not archived).
65 - Enable this if you want to use M(ansible.builtin.unarchive) on an archive of a single file created with this module.
66 type: bool
67 default: false
68 remove:
69 description:
70 - Remove any added source files and trees after adding to archive.
71 type: bool
72 default: false
73 notes:
74 - Can produce C(gzip), C(bzip2), C(lzma), and C(zip) compressed files or archives.
75 - This module uses C(tarfile), C(zipfile), C(gzip), C(bz2), and C(lzma) packages on the target host to create archives. These are
76 part of the Python standard library.
77 seealso:
78 - module: ansible.builtin.unarchive
79 author:
80 - Ben Doherty (@bendoh)
81 """
82
83 EXAMPLES = r"""
84 - name: Compress directory /path/to/foo/ into /path/to/foo.tgz
85 community.general.archive:
86 path: /path/to/foo
87 dest: /path/to/foo.tgz
88
89 - name: Compress regular file /path/to/foo into /path/to/foo.gz and remove it
90 community.general.archive:
91 path: /path/to/foo
92 remove: true
93
94 - name: Create a zip archive of /path/to/foo
95 community.general.archive:
96 path: /path/to/foo
97 format: zip
98
99 - name: Create a bz2 archive of multiple files, rooted at /path
100 community.general.archive:
101 path:
102 - /path/to/foo
103 - /path/wong/foo
104 dest: /path/file.tar.bz2
105 format: bz2
106
107 - name: Create a bz2 archive of a globbed path, while excluding specific dirnames
108 community.general.archive:
109 path:
110 - /path/to/foo/*
111 dest: /path/file.tar.bz2
112 exclude_path:
113 - /path/to/foo/bar
114 - /path/to/foo/baz
115 format: bz2
116
117 - name: Create a bz2 archive of a globbed path, while excluding a glob of dirnames
118 community.general.archive:
119 path:
120 - /path/to/foo/*
121 dest: /path/file.tar.bz2
122 exclude_path:
123 - /path/to/foo/ba*
124 format: bz2
125
126 - name: Use gzip to compress a single archive (i.e don't archive it first with tar)
127 community.general.archive:
128 path: /path/to/foo/single.file
129 dest: /path/file.gz
130 format: gz
131
132 - name: Create a tar.gz archive of a single file.
133 community.general.archive:
134 path: /path/to/foo/single.file
135 dest: /path/file.tar.gz
136 format: gz
137 force_archive: true
138 """
139
140 RETURN = r"""
141 state:
142 description: The state of the input O(path).
143 type: str
144 returned: always
145 dest_state:
146 description:
147 - The state of the O(dest) file.
148 - V(absent) when the file does not exist.
149 - V(archive) when the file is an archive.
150 - V(compress) when the file is compressed, but not an archive.
151 - V(incomplete) when the file is an archive, but some files under O(path) were not found.
152 type: str
153 returned: success
154 version_added: 3.4.0
155 missing:
156 description: Any files that were missing from the source.
157 type: list
158 returned: success
159 archived:
160 description: Any files that were compressed or added to the archive.
161 type: list
162 returned: success
163 arcroot:
164 description: The archive root.
165 type: str
166 returned: always
167 expanded_paths:
168 description: The list of matching paths from paths argument.
169 type: list
170 returned: always
171 expanded_exclude_paths:
172 description: The list of matching exclude paths from the exclude_path argument.
173 type: list
174 returned: always
175 """
176
177 import abc
178 import bz2
179 import glob
180 import gzip
181 import io
182 import lzma
183 import os
184 import re
185 import shutil
186 import tarfile
187 import zipfile
188 from fnmatch import fnmatch
189 from traceback import format_exc
190 from zipfile import BadZipFile
191 from zlib import crc32
192
193 from ansible.module_utils.basic import AnsibleModule
194 from ansible.module_utils.common.text.converters import to_bytes, to_native
195
196 STATE_ABSENT = "absent"
197 STATE_ARCHIVED = "archive"
198 STATE_COMPRESSED = "compress"
199 STATE_INCOMPLETE = "incomplete"
200
201
202 def common_path(paths):
203 empty = b"" if paths and isinstance(paths[0], bytes) else ""
204
205 return os.path.join(
206 os.path.dirname(os.path.commonprefix([os.path.join(os.path.dirname(p), empty) for p in paths])), empty
207 )
208
209
210 def expand_paths(paths):
211 expanded_path = []
212 is_globby = False
213 for path in paths:
214 b_path = _to_bytes(path)
215 if b"*" in b_path or b"?" in b_path:
216 e_paths = glob.glob(b_path)
217 is_globby = True
218 else:
219 e_paths = [b_path]
220 expanded_path.extend(e_paths)
221 return expanded_path, is_globby
222
223
224 def matches_exclusion_patterns(path, exclusion_patterns):
225 return any(fnmatch(path, p) for p in exclusion_patterns)
226
227
228 def is_archive(path):
229 return re.search(rb"\.(tar|tar\.(gz|bz2|xz)|tgz|tbz2|zip)$", os.path.basename(path), re.IGNORECASE)
230
231
232 def strip_prefix(prefix, string):
233 return string[len(prefix) :] if string.startswith(prefix) else string
234
235
236 def _to_bytes(s):
237 return to_bytes(s, errors="surrogate_or_strict")
238
239
240 def _to_native(s):
241 return to_native(s, errors="surrogate_or_strict")
242
243
244 def _to_native_ascii(s):
245 return to_native(s, errors="surrogate_or_strict", encoding="ascii")
246
247
248 class Archive(metaclass=abc.ABCMeta):
249 def __init__(self, module):
250 self.module = module
251
252 self.destination = _to_bytes(module.params["dest"]) if module.params["dest"] else None
253 self.exclusion_patterns = module.params["exclusion_patterns"] or []
254 self.format = module.params["format"]
255 self.must_archive = module.params["force_archive"]
256 self.remove = module.params["remove"]
257
258 self.changed = False
259 self.destination_state = STATE_ABSENT
260 self.errors = []
261 self.file = None
262 self.successes = []
263 self.targets = []
264 self.not_found = []
265
266 paths = module.params["path"]
267 self.expanded_paths, has_globs = expand_paths(paths)
268 self.expanded_exclude_paths = expand_paths(module.params["exclude_path"])[0]
269
270 self.paths = sorted(set(self.expanded_paths) - set(self.expanded_exclude_paths))
271
272 if not self.paths:
273 module.fail_json(
274 path=", ".join(paths),
275 expanded_paths=_to_native(b", ".join(self.expanded_paths)),
276 expanded_exclude_paths=_to_native(b", ".join(self.expanded_exclude_paths)),
277 msg="Error, no source paths were found",
278 )
279
280 self.root = common_path(self.paths)
281
282 if not self.must_archive:
283 self.must_archive = any([has_globs, os.path.isdir(self.paths[0]), len(self.paths) > 1])
284
285 if not self.destination and not self.must_archive:
286 self.destination = b"%s.%s" % (self.paths[0], _to_bytes(self.format))
287
288 if self.must_archive and not self.destination:
289 module.fail_json(
290 dest=_to_native(self.destination),
291 path=", ".join(paths),
292 msg='Error, must specify "dest" when archiving multiple files or trees',
293 )
294
295 if self.remove:
296 self._check_removal_safety()
297
298 self.original_checksums = self.destination_checksums()
299 self.original_size = self.destination_size()
300
301 def add(self, path, archive_name):
302 try:
303 self._add(_to_native_ascii(path), _to_native(archive_name))
304 if self.contains(_to_native(archive_name)):
305 self.successes.append(path)
306 except Exception as e:
307 self.errors.append(f"{_to_native_ascii(path)}: {e}")
308
309 def add_single_target(self, path):
310 if self.format in ("zip", "tar"):
311 self.open()
312 self.add(path, strip_prefix(self.root, path))
313 self.close()
314 self.destination_state = STATE_ARCHIVED
315 else:
316 try:
317 f_out = self._open_compressed_file(_to_native_ascii(self.destination), "wb")
318 with open(path, "rb") as f_in:
319 shutil.copyfileobj(f_in, f_out)
320 f_out.close()
321 self.successes.append(path)
322 self.destination_state = STATE_COMPRESSED
323 except OSError as e:
324 self.module.fail_json(
325 path=_to_native(path),
326 dest=_to_native(self.destination),
327 msg=f"Unable to write to compressed file: {e}",
328 exception=format_exc(),
329 )
330
331 def add_targets(self):
332 self.open()
333 try:
334 for target in self.targets:
335 if os.path.isdir(target):
336 for directory_path, directory_names, file_names in os.walk(target, topdown=True):
337 for directory_name in directory_names:
338 full_path = os.path.join(directory_path, directory_name)
339 self.add(full_path, strip_prefix(self.root, full_path))
340
341 for file_name in file_names:
342 full_path = os.path.join(directory_path, file_name)
343 self.add(full_path, strip_prefix(self.root, full_path))
344 else:
345 self.add(target, strip_prefix(self.root, target))
346 except Exception as e:
347 if self.format in ("zip", "tar"):
348 archive_format = self.format
349 else:
350 archive_format = f"tar.{self.format}"
351 self.module.fail_json(
352 msg=f"Error when writing {archive_format} archive at {_to_native(self.destination)}: {e}",
353 exception=format_exc(),
354 )
355 self.close()
356
357 if self.errors:
358 self.module.fail_json(
359 msg=f"Errors when writing archive at {_to_native(self.destination)}: {'; '.join(self.errors)}"
360 )
361
362 def is_different_from_original(self):
363 if self.original_checksums is None:
364 return self.original_size != self.destination_size()
365 else:
366 return self.original_checksums != self.destination_checksums()
367
368 def destination_checksums(self):
369 if self.destination_exists() and self.destination_readable():
370 return self._get_checksums(self.destination)
371 return None
372
373 def destination_exists(self):
374 return self.destination and os.path.exists(self.destination)
375
376 def destination_readable(self):
377 return self.destination and os.access(self.destination, os.R_OK)
378
379 def destination_size(self):
380 return os.path.getsize(self.destination) if self.destination_exists() else 0
381
382 def find_targets(self):
383 for path in self.paths:
384 if not os.path.lexists(path):
385 self.not_found.append(path)
386 else:
387 self.targets.append(path)
388
389 def has_targets(self):
390 return bool(self.targets)
391
392 def has_unfound_targets(self):
393 return bool(self.not_found)
394
395 def remove_single_target(self, path):
396 try:
397 os.remove(path)
398 except OSError as e:
399 self.module.fail_json(
400 path=_to_native(path), msg=f"Unable to remove source file: {e}", exception=format_exc()
401 )
402
403 def remove_targets(self):
404 for path in self.successes:
405 if os.path.exists(path):
406 try:
407 if os.path.isdir(path):
408 shutil.rmtree(path)
409 else:
410 os.remove(path)
411 except OSError:
412 self.errors.append(_to_native(path))
413 for path in self.paths:
414 try:
415 if os.path.isdir(path):
416 shutil.rmtree(path)
417 except OSError:
418 self.errors.append(_to_native(path))
419
420 if self.errors:
421 self.module.fail_json(
422 dest=_to_native(self.destination), msg="Error deleting some source files: ", files=self.errors
423 )
424
425 def update_permissions(self):
426 file_args = self.module.load_file_common_arguments(self.module.params, path=self.destination)
427 self.changed = self.module.set_fs_attributes_if_different(file_args, self.changed)
428
429 @property
430 def result(self):
431 return {
432 "archived": [_to_native(p) for p in self.successes],
433 "dest": _to_native(self.destination),
434 "dest_state": self.destination_state,
435 "changed": self.changed,
436 "arcroot": _to_native(self.root),
437 "missing": [_to_native(p) for p in self.not_found],
438 "expanded_paths": [_to_native(p) for p in self.expanded_paths],
439 "expanded_exclude_paths": [_to_native(p) for p in self.expanded_exclude_paths],
440 }
441
442 def _check_removal_safety(self):
443 for path in self.paths:
444 if os.path.isdir(path) and self.destination.startswith(os.path.join(path, b"")):
445 self.module.fail_json(
446 path=b", ".join(self.paths),
447 msg="Error, created archive can not be contained in source paths when remove=true",
448 )
449
450 def _open_compressed_file(self, path, mode):
451 f = None
452 if self.format == "gz":
453 f = gzip.open(path, mode)
454 elif self.format == "bz2":
455 f = bz2.BZ2File(path, mode)
456 elif self.format == "xz":
457 f = lzma.LZMAFile(path, mode)
458 else:
459 self.module.fail_json(msg=f"{self.format} is not a valid format")
460
461 return f
462
463 @abc.abstractmethod
464 def close(self):
465 pass
466
467 @abc.abstractmethod
468 def contains(self, name):
469 pass
470
471 @abc.abstractmethod
472 def open(self):
473 pass
474
475 @abc.abstractmethod
476 def _add(self, path, archive_name):
477 pass
478
479 @abc.abstractmethod
480 def _get_checksums(self, path):
481 pass
482
483
484 class ZipArchive(Archive):
485 def __init__(self, module):
486 super().__init__(module)
487
488 def close(self):
489 self.file.close()
490
491 def contains(self, name):
492 try:
493 self.file.getinfo(name)
494 except KeyError:
495 return False
496 return True
497
498 def open(self):
499 self.file = zipfile.ZipFile(_to_native_ascii(self.destination), "w", zipfile.ZIP_DEFLATED, True)
500
501 def _add(self, path, archive_name):
502 if not matches_exclusion_patterns(path, self.exclusion_patterns):
503 self.file.write(path, archive_name)
504
505 def _get_checksums(self, path):
506 try:
507 archive = zipfile.ZipFile(_to_native_ascii(path), "r")
508 checksums = {(info.filename, info.CRC) for info in archive.infolist()}
509 archive.close()
510 except BadZipFile:
511 checksums = set()
512 return checksums
513
514
515 class TarArchive(Archive):
516 def __init__(self, module):
517 super().__init__(module)
518 self.fileIO = None
519
520 def close(self):
521 self.file.close()
522 if self.format == "xz":
523 with lzma.open(_to_native(self.destination), "wb") as f:
524 f.write(self.fileIO.getvalue())
525 self.fileIO.close()
526
527 def contains(self, name):
528 try:
529 self.file.getmember(name)
530 except KeyError:
531 return False
532 return True
533
534 def open(self):
535 if self.format in ("gz", "bz2"):
536 self.file = tarfile.open(_to_native_ascii(self.destination), f"w|{self.format}")
537 # python3 tarfile module allows xz format but for python2 we have to create the tarfile
538 # in memory and then compress it with lzma.
539 elif self.format == "xz":
540 self.fileIO = io.BytesIO()
541 self.file = tarfile.open(fileobj=self.fileIO, mode="w")
542 elif self.format == "tar":
543 self.file = tarfile.open(_to_native_ascii(self.destination), "w")
544 else:
545 self.module.fail_json(msg=f"{self.format} is not a valid archive format")
546
547 def _add(self, path, archive_name):
548 def filter(tarinfo):
549 return None if matches_exclusion_patterns(tarinfo.name, self.exclusion_patterns) else tarinfo
550
551 self.file.add(path, archive_name, recursive=False, filter=filter)
552
553 def _get_checksums(self, path):
554 LZMAError = lzma.LZMAError
555
556 try:
557 if self.format == "xz":
558 with lzma.open(_to_native_ascii(path), "r") as f:
559 archive = tarfile.open(fileobj=f)
560 checksums = {(info.name, info.chksum) for info in archive.getmembers()}
561 archive.close()
562 else:
563 archive = tarfile.open(_to_native_ascii(path), f"r|{self.format}")
564 checksums = {(info.name, info.chksum) for info in archive.getmembers()}
565 archive.close()
566 except (LZMAError, tarfile.ReadError, tarfile.CompressionError):
567 try:
568 # The python implementations of gzip, bz2, and lzma do not support restoring compressed files
569 # to their original names so only file checksum is returned
570 f = self._open_compressed_file(_to_native_ascii(path), "r")
571 checksum = 0
572 while True:
573 chunk = f.read(16 * 1024 * 1024)
574 if not chunk:
575 break
576 checksum = crc32(chunk, checksum)
577 checksums = {(b"", checksum)}
578 f.close()
579 except Exception:
580 checksums = set()
581 return checksums
582
583
584 def get_archive(module):
585 if module.params["format"] == "zip":
586 return ZipArchive(module)
587 else:
588 return TarArchive(module)
589
590
591 def create_module() -> AnsibleModule:
592 module = AnsibleModule(
593 argument_spec=dict(
594 path=dict(type="list", elements="path", required=True),
595 format=dict(type="str", default="gz", choices=["bz2", "gz", "tar", "xz", "zip"]),
596 dest=dict(type="path"),
597 exclude_path=dict(type="list", elements="path", default=[]),
598 exclusion_patterns=dict(type="list", elements="path"),
599 force_archive=dict(type="bool", default=False),
600 remove=dict(type="bool", default=False),
601 ),
602 add_file_common_args=True,
603 supports_check_mode=True,
604 )
605 return module
606
607
608 def main():
609 module = create_module()
610
611 check_mode = module.check_mode
612
613 archive = get_archive(module)
614 archive.find_targets()
615
616 if not archive.has_targets():
617 if archive.destination_exists():
618 archive.destination_state = STATE_ARCHIVED if is_archive(archive.destination) else STATE_COMPRESSED
619 elif archive.has_targets() and archive.must_archive:
620 if check_mode:
621 archive.changed = True
622 else:
623 archive.add_targets()
624 archive.destination_state = STATE_INCOMPLETE if archive.has_unfound_targets() else STATE_ARCHIVED
625 archive.changed |= archive.is_different_from_original()
626 if archive.remove:
627 archive.remove_targets()
628 else:
629 if check_mode:
630 if not archive.destination_exists():
631 archive.changed = True
632 else:
633 path = archive.paths[0]
634 archive.add_single_target(path)
635 archive.changed |= archive.is_different_from_original()
636 if archive.remove:
637 archive.remove_single_target(path)
638
639 if archive.destination_exists():
640 archive.update_permissions()
641
642 module.exit_json(**archive.result)
643
644
645 if __name__ == "__main__":
646 main()