Debian Codegraph @

lib/ansible/plugins/action/copy.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 # (c) 2017 Toshio Kuratomi <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 from __future__ import annotations
20
21 import json
22 import os
23 import os.path
24 import stat
25 import tempfile
26 import typing as _t
27
28 from ansible import constants as C
29 from ansible.errors import AnsibleError, AnsibleActionFail, AnsibleFileNotFound
30 from ansible.module_utils.basic import FILE_COMMON_ARGUMENTS
31 from ansible.module_utils.common.text.converters import to_bytes, to_text
32 from ansible.module_utils.parsing.convert_bool import boolean
33 from ansible.plugins.action import ActionBase
34 from ansible.utils.hashing import checksum
35
36
37 # Supplement the FILE_COMMON_ARGUMENTS with arguments that are specific to file
38 REAL_FILE_ARGS = frozenset(FILE_COMMON_ARGUMENTS.keys()).union(
39 ('state', 'path', '_original_basename', 'recurse', 'force',
40 '_diff_peek', 'src'))
41
42
43 def _create_remote_file_args(module_args):
44 """remove keys that are not relevant to file"""
45 return dict((k, v) for k, v in module_args.items() if k in REAL_FILE_ARGS)
46
47
48 def _create_remote_copy_args(module_args):
49 """remove action plugin only keys"""
50 return dict((k, v) for k, v in module_args.items() if k not in ('content', 'decrypt'))
51
52
53 def _walk_dirs(topdir, base_path=None, local_follow=False, trailing_slash_detector=None):
54 """
55 Walk a filesystem tree returning enough information to copy the files
56
57 :arg topdir: The directory that the filesystem tree is rooted at
58 :kwarg base_path: The initial directory structure to strip off of the
59 files for the destination directory. If this is None (the default),
60 the base_path is set to ``top_dir``.
61 :kwarg local_follow: Whether to follow symlinks on the source. When set
62 to False, no symlinks are dereferenced. When set to True (the
63 default), the code will dereference most symlinks. However, symlinks
64 can still be present if needed to break a circular link.
65 :kwarg trailing_slash_detector: Function to determine if a path has
66 a trailing directory separator. Only needed when dealing with paths on
67 a remote machine (in which case, pass in a function that is aware of the
68 directory separator conventions on the remote machine).
69 :returns: dictionary of tuples. All of the path elements in the structure are text strings.
70 This separates all the files, directories, and symlinks along with
71 important information about each::
72
73 { 'files': [('/absolute/path/to/copy/from', 'relative/path/to/copy/to'), ...],
74 'directories': [('/absolute/path/to/copy/from', 'relative/path/to/copy/to'), ...],
75 'symlinks': [('/symlink/target/path', 'relative/path/to/copy/to'), ...],
76 }
77
78 The ``symlinks`` field is only populated if ``local_follow`` is set to False
79 *or* a circular symlink cannot be dereferenced.
80
81 """
82 # Convert the path segments into byte strings
83
84 r_files = {'files': [], 'directories': [], 'symlinks': []}
85
86 def _recurse(topdir, rel_offset, parent_dirs, rel_base=u''):
87 """
88 This is a closure (function utilizing variables from it's parent
89 function's scope) so that we only need one copy of all the containers.
90 Note that this function uses side effects (See the Variables used from
91 outer scope).
92
93 :arg topdir: The directory we are walking for files
94 :arg rel_offset: Integer defining how many characters to strip off of
95 the beginning of a path
96 :arg parent_dirs: Directories that we're copying that this directory is in.
97 :kwarg rel_base: String to prepend to the path after ``rel_offset`` is
98 applied to form the relative path.
99
100 Variables used from the outer scope
101 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
102
103 :r_files: Dictionary of files in the hierarchy. See the return value
104 for :func:`walk` for the structure of this dictionary.
105 :local_follow: Read-only inside of :func:`_recurse`. Whether to follow symlinks
106 """
107 for base_path, sub_folders, files in os.walk(topdir):
108 for filename in files:
109 filepath = os.path.join(base_path, filename)
110 dest_filepath = os.path.join(rel_base, filepath[rel_offset:])
111
112 if os.path.islink(filepath):
113 # Dereference the symlnk
114 real_file = os.path.realpath(filepath)
115 if local_follow and os.path.isfile(real_file):
116 # Add the file pointed to by the symlink
117 r_files['files'].append((real_file, dest_filepath))
118 else:
119 # Mark this file as a symlink to copy
120 r_files['symlinks'].append((os.readlink(filepath), dest_filepath))
121 else:
122 # Just a normal file
123 r_files['files'].append((filepath, dest_filepath))
124
125 for dirname in sub_folders:
126 dirpath = os.path.join(base_path, dirname)
127 dest_dirpath = os.path.join(rel_base, dirpath[rel_offset:])
128 real_dir = os.path.realpath(dirpath)
129 dir_stats = os.stat(real_dir)
130
131 if os.path.islink(dirpath):
132 if local_follow:
133 if (dir_stats.st_dev, dir_stats.st_ino) in parent_dirs:
134 # Just insert the symlink if the target directory
135 # exists inside of the copy already
136 r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
137 else:
138 # Walk the dirpath to find all parent directories.
139 new_parents = set()
140 parent_dir_list = os.path.dirname(dirpath).split(os.path.sep)
141 for parent in range(len(parent_dir_list), 0, -1):
142 parent_stat = os.stat(u'/'.join(parent_dir_list[:parent]))
143 if (parent_stat.st_dev, parent_stat.st_ino) in parent_dirs:
144 # Reached the point at which the directory
145 # tree is already known. Don't add any
146 # more or we might go to an ancestor that
147 # isn't being copied.
148 break
149 new_parents.add((parent_stat.st_dev, parent_stat.st_ino))
150
151 if (dir_stats.st_dev, dir_stats.st_ino) in new_parents:
152 # This was a circular symlink. So add it as
153 # a symlink
154 r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
155 else:
156 # Walk the directory pointed to by the symlink
157 r_files['directories'].append((real_dir, dest_dirpath))
158 offset = len(real_dir) + 1
159 _recurse(real_dir, offset, parent_dirs.union(new_parents), rel_base=dest_dirpath)
160 else:
161 # Add the symlink to the destination
162 r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
163 else:
164 # Just a normal directory
165 r_files['directories'].append((dirpath, dest_dirpath))
166
167 # Check if the source ends with a "/" so that we know which directory
168 # level to work at (similar to rsync)
169 source_trailing_slash = False
170 if trailing_slash_detector:
171 source_trailing_slash = trailing_slash_detector(topdir)
172 else:
173 source_trailing_slash = topdir.endswith(os.path.sep)
174
175 # Calculate the offset needed to strip the base_path to make relative
176 # paths
177 if base_path is None:
178 base_path = topdir
179 if not source_trailing_slash:
180 base_path = os.path.dirname(base_path)
181 if topdir.startswith(base_path):
182 offset = len(base_path)
183
184 # Make sure we're making the new paths relative
185 if trailing_slash_detector and not trailing_slash_detector(base_path):
186 offset += 1
187 elif not base_path.endswith(os.path.sep):
188 offset += 1
189
190 if os.path.islink(topdir) and not local_follow:
191 r_files['symlinks'] = (os.readlink(topdir), os.path.basename(topdir))
192 return r_files
193
194 dir_stats = os.stat(topdir)
195 parents = frozenset(((dir_stats.st_dev, dir_stats.st_ino),))
196 # Actually walk the directory hierarchy
197 _recurse(topdir, offset, parents)
198
199 return r_files
200
201
202 class ActionModule(ActionBase):
203
204 TRANSFERS_FILES = True
205
206 def _ensure_invocation(self, result: dict[str, _t.Any], task_vars: dict[str, _t.Any] | None = None) -> dict[str, _t.Any]:
207 # NOTE: adding invocation arguments here needs to be kept in sync with
208 # any no_log specified in the argument_spec in the module.
209 # This is not automatic.
210 # NOTE: do not add to this. This should be made a generic function for action plugins.
211 # This should also use the same argspec as the module instead of keeping it in sync.
212 if not C.config.get_config_value('INJECT_INVOCATION', variables=task_vars or {}, templar=self._templar):
213 result.pop('invocation', None)
214 return result
215
216 if 'invocation' not in result:
217 if self._task.no_log:
218 result['invocation'] = "CENSORED: no_log is set"
219 else:
220 # NOTE: Should be removed in the future. For now keep this broken
221 # behaviour, have a look in the PR 51582
222 result['invocation'] = self._task.args.copy()
223 result['invocation']['module_args'] = self._task.args.copy()
224
225 if isinstance(result['invocation'], dict):
226 if 'content' in result['invocation']:
227 result['invocation']['content'] = 'CENSORED: content is a no_log parameter'
228 if result['invocation'].get('module_args', {}).get('content') is not None:
229 result['invocation']['module_args']['content'] = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
230
231 return result
232
233 def _copy_file(self, source_full, source_rel, content, content_tempfile,
234 dest, task_vars, follow):
235 decrypt = boolean(self._task.args.get('decrypt', True), strict=False)
236 force = boolean(self._task.args.get('force', 'yes'), strict=False)
237 raw = boolean(self._task.args.get('raw', 'no'), strict=False)
238
239 result = {}
240 result['diff'] = []
241
242 # If the local file does not exist, get_real_file() raises AnsibleFileNotFound
243 try:
244 source_full = self._loader.get_real_file(source_full, decrypt=decrypt)
245 except AnsibleFileNotFound as e:
246 result['failed'] = True
247 result['msg'] = "could not find src=%s, %s" % (source_full, to_text(e))
248 return result
249
250 # Get the local mode and set if user wanted it preserved
251 # https://github.com/ansible/ansible-modules-core/issues/1124
252 lmode = None
253 if self._task.args.get('mode', None) == 'preserve':
254 lmode = '0%03o' % stat.S_IMODE(os.stat(source_full).st_mode)
255
256 # This is kind of optimization - if user told us destination is
257 # dir, do path manipulation right away, otherwise we still check
258 # for dest being a dir via remote call below.
259 if self._connection._shell.path_has_trailing_slash(dest):
260 dest_file = self._connection._shell.join_path(dest, source_rel)
261 else:
262 dest_file = dest
263
264 # Attempt to get remote file info
265 dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, checksum=force)
266
267 if dest_status['exists'] and dest_status['isdir']:
268 # The dest is a directory.
269 if content is not None:
270 # If source was defined as content remove the temporary file and fail out.
271 self._remove_tempfile_if_content_defined(content, content_tempfile)
272 result['failed'] = True
273 result['msg'] = "can not use content with a dir as dest"
274 return result
275 else:
276 # Append the relative source location to the destination and get remote stats again
277 dest_file = self._connection._shell.join_path(dest, source_rel)
278 dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, checksum=force)
279
280 if dest_status['exists'] and not force:
281 # remote_file exists so continue to next iteration.
282 return None
283
284 # Generate a hash of the local file.
285 local_checksum = checksum(source_full)
286
287 if local_checksum != dest_status['checksum']:
288 # The checksums don't match and we will change or error out.
289
290 if self._task.diff and not raw:
291 result['diff'].append(self._get_diff_data(dest_file, source_full, task_vars, content))
292
293 if self._task.check_mode:
294 self._remove_tempfile_if_content_defined(content, content_tempfile)
295 result['changed'] = True
296 return result
297
298 # Define a remote directory that we will copy the file to.
299 tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir, '.source')
300
301 # ensure we keep suffix for validate
302 suffix = os.path.splitext(dest_file)[1]
303 if suffix:
304 tmp_src += suffix
305
306 remote_path = None
307
308 if not raw:
309 remote_path = self._transfer_file(source_full, tmp_src)
310 else:
311 self._transfer_file(source_full, dest_file)
312
313 # We have copied the file remotely and no longer require our content_tempfile
314 self._remove_tempfile_if_content_defined(content, content_tempfile)
315 self._loader.cleanup_tmp_file(source_full)
316
317 # FIXME: I don't think this is needed when PIPELINING=0 because the source is created
318 # world readable. Access to the directory itself is controlled via fixup_perms2() as
319 # part of executing the module. Check that umask with scp/sftp/piped doesn't cause
320 # a problem before acting on this idea. (This idea would save a round-trip)
321 # fix file permissions when the copy is done as a different user
322 if remote_path:
323 self._fixup_perms2((self._connection._shell.tmpdir, remote_path))
324
325 if raw:
326 # Continue to next iteration if raw is defined.
327 return None
328
329 # Run the copy module
330
331 # src and dest here come after original and override them
332 # we pass dest only to make sure it includes trailing slash in case of recursive copy
333 new_module_args = _create_remote_copy_args(self._task.args)
334 new_module_args.update(
335 dict(
336 src=tmp_src,
337 dest=dest,
338 _original_basename=source_rel,
339 follow=follow
340 )
341 )
342 if not self._task.args.get('checksum'):
343 new_module_args['checksum'] = local_checksum
344
345 if lmode:
346 new_module_args['mode'] = lmode
347
348 module_return = self._execute_module(module_name='ansible.legacy.copy', module_args=new_module_args, task_vars=task_vars)
349
350 else:
351 # no need to transfer the file, already correct hash, but still need to call
352 # the file module in case we want to change attributes
353 self._remove_tempfile_if_content_defined(content, content_tempfile)
354 self._loader.cleanup_tmp_file(source_full)
355
356 if raw:
357 return None
358
359 # Fix for https://github.com/ansible/ansible-modules-core/issues/1568.
360 # If checksums match, and follow = True, find out if 'dest' is a link. If so,
361 # change it to point to the source of the link.
362 if follow:
363 dest_status_nofollow = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=False)
364 if dest_status_nofollow['islnk'] and 'lnk_source' in dest_status_nofollow.keys():
365 dest = dest_status_nofollow['lnk_source']
366
367 # Build temporary module_args.
368 new_module_args = _create_remote_file_args(self._task.args)
369 new_module_args.update(
370 dict(
371 dest=dest,
372 _original_basename=source_rel,
373 recurse=False,
374 state='file',
375 )
376 )
377 # src is sent to the file module in _original_basename, not in src
378 try:
379 del new_module_args['src']
380 except KeyError:
381 pass
382
383 if lmode:
384 new_module_args['mode'] = lmode
385
386 # Execute the file module.
387 module_return = self._execute_module(module_name='ansible.legacy.file', module_args=new_module_args, task_vars=task_vars)
388
389 if not module_return.get('checksum'):
390 module_return['checksum'] = local_checksum
391
392 result.update(module_return)
393 return result
394
395 def _create_content_tempfile(self, content):
396 """ Create a tempfile containing defined content """
397 fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP, prefix='.')
398 content = to_bytes(content)
399 try:
400 with os.fdopen(fd, 'wb') as f:
401 f.write(content)
402 except Exception as err:
403 os.remove(content_tempfile)
404 raise Exception(err)
405 return content_tempfile
406
407 def _remove_tempfile_if_content_defined(self, content, content_tempfile):
408 if content is not None:
409 os.remove(content_tempfile)
410
411 def run(self, tmp=None, task_vars=None):
412 try:
413 result = self._run(task_vars=task_vars)
414 return self._ensure_invocation(result, task_vars=task_vars)
415 except AnsibleActionFail as aaf:
416 # twiddle `invocation` on the stored result, if any
417 self._ensure_invocation(aaf.result, task_vars=task_vars)
418 raise
419
420 def _run(self, tmp=None, task_vars=None):
421 """ handler for file transfer operations """
422 if task_vars is None:
423 task_vars = dict()
424
425 result = super(ActionModule, self).run(tmp, task_vars)
426
427 del tmp # tmp no longer has any effect
428
429 # ensure user is not setting internal parameters
430 for internal in ('_original_basename', '_diff_peek'):
431 if self._task.args.get(internal, None) is not None:
432 raise AnsibleActionFail(f'Invalid parameter specified: "{internal}"')
433
434 source = self._task.args.get('src', None)
435 content = self._task.args.get('content', None)
436 dest = self._task.args.get('dest', None)
437 remote_src = boolean(self._task.args.get('remote_src', False), strict=False)
438 local_follow = boolean(self._task.args.get('local_follow', True), strict=False)
439
440 result['failed'] = True
441 if not source and content is None:
442 result['msg'] = 'src (or content) is required'
443 elif not dest:
444 result['msg'] = 'dest is required'
445 elif source and content is not None:
446 result['msg'] = 'src and content are mutually exclusive'
447 elif content is not None and dest is not None and dest.endswith("/"):
448 result['msg'] = "can not use content with a dir as dest"
449 else:
450 del result['failed']
451
452 if result.get('failed'):
453 return result
454
455 # Define content_tempfile in case we set it after finding content populated.
456 content_tempfile = None
457
458 # If content is defined make a tmp file and write the content into it.
459 if content is not None:
460 try:
461 # If content comes to us as a dict it should be decoded json.
462 # We need to encode it back into a string to write it out.
463 if isinstance(content, dict) or isinstance(content, list):
464 content_tempfile = self._create_content_tempfile(json.dumps(content))
465 else:
466 content_tempfile = self._create_content_tempfile(content)
467 source = content_tempfile
468 except Exception as ex:
469 raise AnsibleActionFail(message="could not write content temp file", result=result) from ex
470
471 # if we have first_available_file in our vars
472 # look up the files and use the first one we find as src
473 elif remote_src:
474 result.update(self._execute_module(module_name='ansible.legacy.copy', task_vars=task_vars))
475 return result
476 else:
477 # find_needle returns a path that may not have a trailing slash on
478 # a directory so we need to determine that now (we use it just
479 # like rsync does to figure out whether to include the directory
480 # or only the files inside the directory
481 trailing_slash = source.endswith(os.path.sep)
482 try:
483 # find in expected paths
484 source = self._find_needle('files', source)
485 except AnsibleError as ex:
486 raise AnsibleActionFail(result=result) from ex
487
488 if trailing_slash != source.endswith(os.path.sep):
489 if source[-1] == os.path.sep:
490 source = source[:-1]
491 else:
492 source = source + os.path.sep
493
494 # A list of source file tuples (full_path, relative_path) which will try to copy to the destination
495 source_files = {'files': [], 'directories': [], 'symlinks': []}
496
497 # If source is a directory populate our list else source is a file and translate it to a tuple.
498 if os.path.isdir(to_bytes(source, errors='surrogate_or_strict')):
499 # Get a list of the files we want to replicate on the remote side
500 source_files = _walk_dirs(source, local_follow=local_follow,
501 trailing_slash_detector=self._connection._shell.path_has_trailing_slash)
502
503 # If it's recursive copy, destination is always a dir,
504 # explicitly mark it so (note - copy module relies on this).
505 if not self._connection._shell.path_has_trailing_slash(dest):
506 dest = self._connection._shell.join_path(dest, '')
507 # FIXME: Can we optimize cases where there's only one file, no
508 # symlinks and any number of directories? In the original code,
509 # empty directories are not copied....
510 else:
511 source_files['files'] = [(source, os.path.basename(source))]
512
513 changed = False
514 module_return = dict(changed=False)
515
516 # A register for if we executed a module.
517 # Used to cut down on command calls when not recursive.
518 module_executed = False
519
520 # expand any user home dir specifier
521 dest = self._remote_expand_user(dest)
522
523 implicit_directories = set()
524 for source_full, source_rel in source_files['files']:
525 # copy files over. This happens first as directories that have
526 # a file do not need to be created later
527
528 # We only follow symlinks for files in the non-recursive case
529 if source_files['directories']:
530 follow = False
531 else:
532 follow = boolean(self._task.args.get('follow', False), strict=False)
533
534 module_return = self._copy_file(source_full, source_rel, content, content_tempfile, dest, task_vars, follow)
535 if module_return is None:
536 continue
537
538 if module_return.get('failed'):
539 result.update(module_return)
540 return result
541
542 while (source_rel := os.path.dirname(source_rel)) != '':
543 implicit_directories.add(source_rel)
544
545 if 'diff' in result and not result['diff']:
546 del result['diff']
547 module_executed = True
548 changed = changed or module_return.get('changed', False)
549
550 for src, dest_path in source_files['directories']:
551 # Find directories that are leaves as they might not have been
552 # created yet.
553 if dest_path in implicit_directories:
554 continue
555
556 # Use file module to create these
557 new_module_args = _create_remote_file_args(self._task.args)
558 new_module_args['path'] = os.path.join(dest, dest_path)
559 new_module_args['state'] = 'directory'
560 new_module_args['mode'] = self._task.args.get('directory_mode', None)
561 new_module_args['recurse'] = False
562 del new_module_args['src']
563
564 module_return = self._execute_module(module_name='ansible.legacy.file', module_args=new_module_args, task_vars=task_vars)
565
566 if module_return.get('failed'):
567 result.update(module_return)
568 return result
569
570 module_executed = True
571 changed = changed or module_return.get('changed', False)
572
573 for target_path, dest_path in source_files['symlinks']:
574 # Copy symlinks over
575 new_module_args = _create_remote_file_args(self._task.args)
576 new_module_args['path'] = os.path.join(dest, dest_path)
577 new_module_args['src'] = target_path
578 new_module_args['state'] = 'link'
579 new_module_args['force'] = True
580
581 # Only follow remote symlinks in the non-recursive case
582 if source_files['directories']:
583 new_module_args['follow'] = False
584
585 # file module cannot deal with 'preserve' mode and is meaningless
586 # for symlinks anyway, so just don't pass it.
587 if new_module_args.get('mode', None) == 'preserve':
588 new_module_args.pop('mode')
589
590 module_return = self._execute_module(module_name='ansible.legacy.file', module_args=new_module_args, task_vars=task_vars)
591 module_executed = True
592
593 if module_return.get('failed'):
594 result.update(module_return)
595 return result
596
597 changed = changed or module_return.get('changed', False)
598
599 if module_executed and len(source_files['files']) == 1:
600 result.update(module_return)
601
602 # the file module returns the file path as 'path', but
603 # the copy module uses 'dest', so add it if it's not there
604 if 'path' in result and 'dest' not in result:
605 result['dest'] = result['path']
606 else:
607 result.update(dict(dest=dest, src=source, changed=changed))
608
609 # Delete tmp path
610 self._remove_tmp_path(self._connection._shell.tmpdir)
611
612 return result