Debian Codegraph @

test/support/windows-integration/plugins/action/win_copy.py

raw
1 # This file is part of Ansible
2
3 # Copyright (c) 2017 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import base64
9 import json
10 import os
11 import os.path
12 import shutil
13 import tempfile
14 import traceback
15 import zipfile
16
17 from ansible import constants as C
18 from ansible.errors import AnsibleError, AnsibleFileNotFound
19 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
20 from ansible.module_utils.parsing.convert_bool import boolean
21 from ansible.plugins.action import ActionBase
22 from ansible.utils.hashing import checksum
23
24
25 def _walk_dirs(topdir, loader, decrypt=True, base_path=None, local_follow=False, trailing_slash_detector=None, checksum_check=False):
26 """
27 Walk a filesystem tree returning enough information to copy the files.
28 This is similar to the _walk_dirs function in ``copy.py`` but returns
29 a dict instead of a tuple for each entry and includes the checksum of
30 a local file if wanted.
31
32 :arg topdir: The directory that the filesystem tree is rooted at
33 :arg loader: The self._loader object from ActionBase
34 :kwarg decrypt: Whether to decrypt a file encrypted with ansible-vault
35 :kwarg base_path: The initial directory structure to strip off of the
36 files for the destination directory. If this is None (the default),
37 the base_path is set to ``top_dir``.
38 :kwarg local_follow: Whether to follow symlinks on the source. When set
39 to False, no symlinks are dereferenced. When set to True (the
40 default), the code will dereference most symlinks. However, symlinks
41 can still be present if needed to break a circular link.
42 :kwarg trailing_slash_detector: Function to determine if a path has
43 a trailing directory separator. Only needed when dealing with paths on
44 a remote machine (in which case, pass in a function that is aware of the
45 directory separator conventions on the remote machine).
46 :kawrg whether to get the checksum of the local file and add to the dict
47 :returns: dictionary of dictionaries. All of the path elements in the structure are text string.
48 This separates all the files, directories, and symlinks along with
49 import information about each::
50
51 {
52 'files'; [{
53 src: '/absolute/path/to/copy/from',
54 dest: 'relative/path/to/copy/to',
55 checksum: 'b54ba7f5621240d403f06815f7246006ef8c7d43'
56 }, ...],
57 'directories'; [{
58 src: '/absolute/path/to/copy/from',
59 dest: 'relative/path/to/copy/to'
60 }, ...],
61 'symlinks'; [{
62 src: '/symlink/target/path',
63 dest: 'relative/path/to/copy/to'
64 }, ...],
65
66 }
67
68 The ``symlinks`` field is only populated if ``local_follow`` is set to False
69 *or* a circular symlink cannot be dereferenced. The ``checksum`` entry is set
70 to None if checksum_check=False.
71
72 """
73 # Convert the path segments into byte strings
74
75 r_files = {'files': [], 'directories': [], 'symlinks': []}
76
77 def _recurse(topdir, rel_offset, parent_dirs, rel_base=u'', checksum_check=False):
78 """
79 This is a closure (function utilizing variables from it's parent
80 function's scope) so that we only need one copy of all the containers.
81 Note that this function uses side effects (See the Variables used from
82 outer scope).
83
84 :arg topdir: The directory we are walking for files
85 :arg rel_offset: Integer defining how many characters to strip off of
86 the beginning of a path
87 :arg parent_dirs: Directories that we're copying that this directory is in.
88 :kwarg rel_base: String to prepend to the path after ``rel_offset`` is
89 applied to form the relative path.
90
91 Variables used from the outer scope
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93
94 :r_files: Dictionary of files in the hierarchy. See the return value
95 for :func:`walk` for the structure of this dictionary.
96 :local_follow: Read-only inside of :func:`_recurse`. Whether to follow symlinks
97 """
98 for base_path, sub_folders, files in os.walk(topdir):
99 for filename in files:
100 filepath = os.path.join(base_path, filename)
101 dest_filepath = os.path.join(rel_base, filepath[rel_offset:])
102
103 if os.path.islink(filepath):
104 # Dereference the symlnk
105 real_file = loader.get_real_file(os.path.realpath(filepath), decrypt=decrypt)
106 if local_follow and os.path.isfile(real_file):
107 # Add the file pointed to by the symlink
108 r_files['files'].append(
109 {
110 "src": real_file,
111 "dest": dest_filepath,
112 "checksum": _get_local_checksum(checksum_check, real_file)
113 }
114 )
115 else:
116 # Mark this file as a symlink to copy
117 r_files['symlinks'].append({"src": os.readlink(filepath), "dest": dest_filepath})
118 else:
119 # Just a normal file
120 real_file = loader.get_real_file(filepath, decrypt=decrypt)
121 r_files['files'].append(
122 {
123 "src": real_file,
124 "dest": dest_filepath,
125 "checksum": _get_local_checksum(checksum_check, real_file)
126 }
127 )
128
129 for dirname in sub_folders:
130 dirpath = os.path.join(base_path, dirname)
131 dest_dirpath = os.path.join(rel_base, dirpath[rel_offset:])
132 real_dir = os.path.realpath(dirpath)
133 dir_stats = os.stat(real_dir)
134
135 if os.path.islink(dirpath):
136 if local_follow:
137 if (dir_stats.st_dev, dir_stats.st_ino) in parent_dirs:
138 # Just insert the symlink if the target directory
139 # exists inside of the copy already
140 r_files['symlinks'].append({"src": os.readlink(dirpath), "dest": dest_dirpath})
141 else:
142 # Walk the dirpath to find all parent directories.
143 new_parents = set()
144 parent_dir_list = os.path.dirname(dirpath).split(os.path.sep)
145 for parent in range(len(parent_dir_list), 0, -1):
146 parent_stat = os.stat(u'/'.join(parent_dir_list[:parent]))
147 if (parent_stat.st_dev, parent_stat.st_ino) in parent_dirs:
148 # Reached the point at which the directory
149 # tree is already known. Don't add any
150 # more or we might go to an ancestor that
151 # isn't being copied.
152 break
153 new_parents.add((parent_stat.st_dev, parent_stat.st_ino))
154
155 if (dir_stats.st_dev, dir_stats.st_ino) in new_parents:
156 # This was a circular symlink. So add it as
157 # a symlink
158 r_files['symlinks'].append({"src": os.readlink(dirpath), "dest": dest_dirpath})
159 else:
160 # Walk the directory pointed to by the symlink
161 r_files['directories'].append({"src": real_dir, "dest": dest_dirpath})
162 offset = len(real_dir) + 1
163 _recurse(real_dir, offset, parent_dirs.union(new_parents),
164 rel_base=dest_dirpath,
165 checksum_check=checksum_check)
166 else:
167 # Add the symlink to the destination
168 r_files['symlinks'].append({"src": os.readlink(dirpath), "dest": dest_dirpath})
169 else:
170 # Just a normal directory
171 r_files['directories'].append({"src": dirpath, "dest": dest_dirpath})
172
173 # Check if the source ends with a "/" so that we know which directory
174 # level to work at (similar to rsync)
175 source_trailing_slash = False
176 if trailing_slash_detector:
177 source_trailing_slash = trailing_slash_detector(topdir)
178 else:
179 source_trailing_slash = topdir.endswith(os.path.sep)
180
181 # Calculate the offset needed to strip the base_path to make relative
182 # paths
183 if base_path is None:
184 base_path = topdir
185 if not source_trailing_slash:
186 base_path = os.path.dirname(base_path)
187 if topdir.startswith(base_path):
188 offset = len(base_path)
189
190 # Make sure we're making the new paths relative
191 if trailing_slash_detector and not trailing_slash_detector(base_path):
192 offset += 1
193 elif not base_path.endswith(os.path.sep):
194 offset += 1
195
196 if os.path.islink(topdir) and not local_follow:
197 r_files['symlinks'] = {"src": os.readlink(topdir), "dest": os.path.basename(topdir)}
198 return r_files
199
200 dir_stats = os.stat(topdir)
201 parents = frozenset(((dir_stats.st_dev, dir_stats.st_ino),))
202 # Actually walk the directory hierarchy
203 _recurse(topdir, offset, parents, checksum_check=checksum_check)
204
205 return r_files
206
207
208 def _get_local_checksum(get_checksum, local_path):
209 if get_checksum:
210 return checksum(local_path)
211 else:
212 return None
213
214
215 class ActionModule(ActionBase):
216
217 WIN_PATH_SEPARATOR = "\\"
218
219 def _create_content_tempfile(self, content):
220 """ Create a tempfile containing defined content """
221 fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
222 content = to_bytes(content)
223 try:
224 with os.fdopen(fd, 'wb') as f:
225 f.write(content)
226 except Exception as err:
227 os.remove(content_tempfile)
228 raise Exception(err)
229 return content_tempfile
230
231 def _create_zip_tempfile(self, files, directories):
232 tmpdir = tempfile.mkdtemp(dir=C.DEFAULT_LOCAL_TMP)
233 zip_file_path = os.path.join(tmpdir, "win_copy.zip")
234 zip_file = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_STORED, True)
235
236 # encoding the file/dir name with base64 so Windows can unzip a unicode
237 # filename and get the right name, Windows doesn't handle unicode names
238 # very well
239 for directory in directories:
240 directory_path = to_bytes(directory['src'], errors='surrogate_or_strict')
241 archive_path = to_bytes(directory['dest'], errors='surrogate_or_strict')
242
243 encoded_path = to_text(base64.b64encode(archive_path), errors='surrogate_or_strict')
244 zip_file.write(directory_path, encoded_path, zipfile.ZIP_DEFLATED)
245
246 for file in files:
247 file_path = to_bytes(file['src'], errors='surrogate_or_strict')
248 archive_path = to_bytes(file['dest'], errors='surrogate_or_strict')
249
250 encoded_path = to_text(base64.b64encode(archive_path), errors='surrogate_or_strict')
251 zip_file.write(file_path, encoded_path, zipfile.ZIP_DEFLATED)
252
253 return zip_file_path
254
255 def _remove_tempfile_if_content_defined(self, content, content_tempfile):
256 if content is not None:
257 os.remove(content_tempfile)
258
259 def _copy_single_file(self, local_file, dest, source_rel, task_vars, tmp, backup):
260 if self._play_context.check_mode:
261 module_return = dict(changed=True)
262 return module_return
263
264 # copy the file across to the server
265 tmp_src = self._connection._shell.join_path(tmp, 'source')
266 self._transfer_file(local_file, tmp_src)
267
268 copy_args = self._task.args.copy()
269 copy_args.update(
270 dict(
271 dest=dest,
272 src=tmp_src,
273 _original_basename=source_rel,
274 _copy_mode="single",
275 backup=backup,
276 )
277 )
278 copy_args.pop('content', None)
279
280 copy_result = self._execute_module(module_name="copy",
281 module_args=copy_args,
282 task_vars=task_vars)
283
284 return copy_result
285
286 def _copy_zip_file(self, dest, files, directories, task_vars, tmp, backup):
287 # create local zip file containing all the files and directories that
288 # need to be copied to the server
289 if self._play_context.check_mode:
290 module_return = dict(changed=True)
291 return module_return
292
293 try:
294 zip_file = self._create_zip_tempfile(files, directories)
295 except Exception as e:
296 module_return = dict(
297 changed=False,
298 failed=True,
299 msg="failed to create tmp zip file: %s" % to_text(e),
300 exception=traceback.format_exc()
301 )
302 return module_return
303
304 zip_path = self._loader.get_real_file(zip_file)
305
306 # send zip file to remote, file must end in .zip so
307 # Com Shell.Application works
308 tmp_src = self._connection._shell.join_path(tmp, 'source.zip')
309 self._transfer_file(zip_path, tmp_src)
310
311 # run the explode operation of win_copy on remote
312 copy_args = self._task.args.copy()
313 copy_args.update(
314 dict(
315 src=tmp_src,
316 dest=dest,
317 _copy_mode="explode",
318 backup=backup,
319 )
320 )
321 copy_args.pop('content', None)
322 module_return = self._execute_module(module_name='copy',
323 module_args=copy_args,
324 task_vars=task_vars)
325 shutil.rmtree(os.path.dirname(zip_path))
326 return module_return
327
328 def run(self, tmp=None, task_vars=None):
329 """ handler for file transfer operations """
330 if task_vars is None:
331 task_vars = dict()
332
333 result = super(ActionModule, self).run(tmp, task_vars)
334 del tmp # tmp no longer has any effect
335
336 source = self._task.args.get('src', None)
337 content = self._task.args.get('content', None)
338 dest = self._task.args.get('dest', None)
339 remote_src = boolean(self._task.args.get('remote_src', False), strict=False)
340 local_follow = boolean(self._task.args.get('local_follow', False), strict=False)
341 force = boolean(self._task.args.get('force', True), strict=False)
342 decrypt = boolean(self._task.args.get('decrypt', True), strict=False)
343 backup = boolean(self._task.args.get('backup', False), strict=False)
344
345 result['src'] = source
346 result['dest'] = dest
347
348 result['failed'] = True
349 if (source is None and content is None) or dest is None:
350 result['msg'] = "src (or content) and dest are required"
351 elif source is not None and content is not None:
352 result['msg'] = "src and content are mutually exclusive"
353 elif content is not None and dest is not None and (
354 dest.endswith(os.path.sep) or dest.endswith(self.WIN_PATH_SEPARATOR)):
355 result['msg'] = "dest must be a file if content is defined"
356 else:
357 del result['failed']
358
359 if result.get('failed'):
360 return result
361
362 # If content is defined make a temp file and write the content into it
363 content_tempfile = None
364 if content is not None:
365 try:
366 # if content comes to us as a dict it should be decoded json.
367 # We need to encode it back into a string and write it out
368 if isinstance(content, dict) or isinstance(content, list):
369 content_tempfile = self._create_content_tempfile(json.dumps(content))
370 else:
371 content_tempfile = self._create_content_tempfile(content)
372 source = content_tempfile
373 except Exception as err:
374 result['failed'] = True
375 result['msg'] = "could not write content tmp file: %s" % to_native(err)
376 return result
377 # all actions should occur on the remote server, run win_copy module
378 elif remote_src:
379 new_module_args = self._task.args.copy()
380 new_module_args.update(
381 dict(
382 _copy_mode="remote",
383 dest=dest,
384 src=source,
385 force=force,
386 backup=backup,
387 )
388 )
389 new_module_args.pop('content', None)
390 result.update(self._execute_module(module_args=new_module_args, task_vars=task_vars))
391 return result
392 # find_needle returns a path that may not have a trailing slash on a
393 # directory so we need to find that out first and append at the end
394 else:
395 trailing_slash = source.endswith(os.path.sep)
396 try:
397 # find in expected paths
398 source = self._find_needle('files', source)
399 except AnsibleError as e:
400 result['failed'] = True
401 result['msg'] = to_text(e)
402 result['exception'] = traceback.format_exc()
403 return result
404
405 if trailing_slash != source.endswith(os.path.sep):
406 if source[-1] == os.path.sep:
407 source = source[:-1]
408 else:
409 source = source + os.path.sep
410
411 # A list of source file tuples (full_path, relative_path) which will try to copy to the destination
412 source_files = {'files': [], 'directories': [], 'symlinks': []}
413
414 # If source is a directory populate our list else source is a file and translate it to a tuple.
415 if os.path.isdir(to_bytes(source, errors='surrogate_or_strict')):
416 result['operation'] = 'folder_copy'
417
418 # Get a list of the files we want to replicate on the remote side
419 source_files = _walk_dirs(source, self._loader, decrypt=decrypt, local_follow=local_follow,
420 trailing_slash_detector=self._connection._shell.path_has_trailing_slash,
421 checksum_check=force)
422
423 # If it's recursive copy, destination is always a dir,
424 # explicitly mark it so (note - win_copy module relies on this).
425 if not self._connection._shell.path_has_trailing_slash(dest):
426 dest = "%s%s" % (dest, self.WIN_PATH_SEPARATOR)
427
428 check_dest = dest
429 # Source is a file, add details to source_files dict
430 else:
431 result['operation'] = 'file_copy'
432
433 # If the local file does not exist, get_real_file() raises AnsibleFileNotFound
434 try:
435 source_full = self._loader.get_real_file(source, decrypt=decrypt)
436 except AnsibleFileNotFound as e:
437 result['failed'] = True
438 result['msg'] = "could not find src=%s, %s" % (source, to_text(e))
439 return result
440
441 original_basename = os.path.basename(source)
442 result['original_basename'] = original_basename
443
444 # check if dest ends with / or \ and append source filename to dest
445 if self._connection._shell.path_has_trailing_slash(dest):
446 check_dest = dest
447 filename = original_basename
448 result['dest'] = self._connection._shell.join_path(dest, filename)
449 else:
450 # replace \\ with / so we can use os.path to get the filename or dirname
451 unix_path = dest.replace(self.WIN_PATH_SEPARATOR, os.path.sep)
452 filename = os.path.basename(unix_path)
453 check_dest = os.path.dirname(unix_path)
454
455 file_checksum = _get_local_checksum(force, source_full)
456 source_files['files'].append(
457 dict(
458 src=source_full,
459 dest=filename,
460 checksum=file_checksum
461 )
462 )
463 result['checksum'] = file_checksum
464 result['size'] = os.path.getsize(to_bytes(source_full, errors='surrogate_or_strict'))
465
466 # find out the files/directories/symlinks that we need to copy to the server
467 query_args = self._task.args.copy()
468 query_args.update(
469 dict(
470 _copy_mode="query",
471 dest=check_dest,
472 force=force,
473 files=source_files['files'],
474 directories=source_files['directories'],
475 symlinks=source_files['symlinks'],
476 )
477 )
478 # src is not required for query, will fail path validation is src has unix allowed chars
479 query_args.pop('src', None)
480
481 query_args.pop('content', None)
482 query_return = self._execute_module(module_args=query_args,
483 task_vars=task_vars)
484
485 if query_return.get('failed') is True:
486 result.update(query_return)
487 return result
488
489 if len(query_return['files']) > 0 or len(query_return['directories']) > 0 and self._connection._shell.tmpdir is None:
490 self._connection._shell.tmpdir = self._make_tmp_path()
491
492 if len(query_return['files']) == 1 and len(query_return['directories']) == 0:
493 # we only need to copy 1 file, don't mess around with zips
494 file_src = query_return['files'][0]['src']
495 file_dest = query_return['files'][0]['dest']
496 result.update(self._copy_single_file(file_src, dest, file_dest,
497 task_vars, self._connection._shell.tmpdir, backup))
498 if result.get('failed') is True:
499 result['msg'] = "failed to copy file %s: %s" % (file_src, result['msg'])
500 result['changed'] = True
501
502 elif len(query_return['files']) > 0 or len(query_return['directories']) > 0:
503 # either multiple files or directories need to be copied, compress
504 # to a zip and 'explode' the zip on the server
505 # TODO: handle symlinks
506 result.update(self._copy_zip_file(dest, source_files['files'],
507 source_files['directories'],
508 task_vars, self._connection._shell.tmpdir, backup))
509 result['changed'] = True
510 else:
511 # no operations need to occur
512 result['failed'] = False
513 result['changed'] = False
514
515 # remove the content tmp file and remote tmp file if it was created
516 self._remove_tempfile_if_content_defined(content, content_tempfile)
517 self._remove_tmp_path(self._connection._shell.tmpdir)
518 return result